Improvements to .each()

Improvements to .each()


This is the current .each() function:
-------------------------------------------------
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
if ( length === undefined ) {
for ( name in object )
if ( callback.apply( object[ name ], args ) === false )
break;
} else
for ( ; i < length; )
if ( callback.apply( object[ i++ ], args ) === false )
break;
// A special, fast, case for the most common use of each
} else {
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] )
=== false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false;
value = object[++i] ){}
}
-------------------------------------------------
First, the only place I could find that calls each() with an "args"
argument is in the ajax load() function:
self.each( callback, [res.responseText, status, res] );
(hopefully this really is the only place each() is called like this,
but if not then perhaps this is a moot point)
The entire first half of the each() method could be removed by using
code like this in load() instead:
self.each( function() {
callback.call(this,res.responseText,status,res);
});
Second, this bug: http://dev.jquery.com/ticket/4366
which is addressed in this thread: http://groups.google.com/group/comp.lang.javascript/msg/468705660cc10d82
talks about a bug in each() that can be fixed by changing the loop
structure.
This clarifies the loop structure that is there, and assures the code
won't break in cases like that noted in the bug report.
The result would be something like this:
-------------------------------------------------
each: function( object, callback ) {
var name, i = 0, length = object.length;
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) ===
false )
break;
} else {
for ( i=0; i<length; i++) {
var value= object[0];
if ( callback.call( value, i, value ) === false )
break;
}
}
}
-------------------------------------------------
Finally, in this recent thread, someone raised the idea of accessing
the whole collection from within the callback function:
http://groups.google.com/group/jquery-en/browse_thread/thread/b4945457c20aa21b/0b20ebdc9c517d0c
This could easily be done by adding:
-------------------------------------------------
each: function( object, callback ) {
var name, i = 0, length = object.length;
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ],
object ) === false )
break;
} else {
for ( i=0; i<length; i++) {
var value= object[0];
if ( callback.call( value, i, value, object ) === false )
break;
}
}
}
-------------------------------------------------
The result would be a shorter, bug-fixed, enhanced each() method.
Thoughts?
Matt Kruse