Skip to main content

Bug Tracker

Side navigation

#14841 closed feature (plugin)

Opened March 03, 2014 06:24PM UTC

Closed March 03, 2014 07:09PM UTC

Allow `each` to accept optional context parameter

Reported by: isochronous Owned by:
Priority: undecided Milestone: None
Component: unfiled Version: 1.11.0-rc1
Keywords: Cc:
Blocked by: Blocking:
Description

First off, I know that there are several ways of accomplishing this already: closures, function.bind, $.proxy, var $self = this, etc. This would merely be a convenience method for a situation I find myself dealing with often.

Essentially, .each should accept an optional third parameter that specifies the context on which the callback method should execute.

#!js
each: function( callback, args, context ) {
    return jQuery.each( this, callback, args );
},

/* snip */

each: function( obj, callback, args, ctx ) {
    var value,
        i = 0,
        length = obj.length,
        isArray = isArraylike( obj );

    if ( args ) {
        if ( isArray ) {
            for ( ; i < length; i++ ) {
                value = callback.apply( ctx || obj[ i ], args );

                if ( value === false ) {
                    break;
                }
            }
        } else {
            for ( i in obj ) {
                value = callback.apply( ctx ||  obj[ i ], args );

                if ( value === false ) {
                    break;
                }
            }
        }

    // A special, fast, case for the most common use of each
    } else {
        if ( isArray ) {
            for ( ; i < length; i++ ) {
                value = callback.call( ctx ||  obj[ i ], i, obj[ i ] );

                if ( value === false ) {
                    break;
                }
            }
        } else {
            for ( i in obj ) {
                value = callback.call( ctx ||  obj[ i ], i, obj[ i ] );

                if ( value === false ) {
                    break;
                }
            }
        }
    }

    return obj;
},
Attachments (0)
Change History (1)

Changed March 03, 2014 07:09PM UTC by dmethvin comment:1

resolution: → plugin
status: newclosed

A feature like this isn't required by our internal uses, and as you say there are plenty of ways to accomplish this already. We don't tend to embellish our well-established utility methods at this point. You could always do this with a plugin.