[jQuery] Breakable Each
[jQuery] Breakable Each
It seems like it would be really easy to implement a breaking mechanism
for jQuery .each() function. We could use the same technique prototype
does by creating a unique object and letting users throw that to break.
We could create a 'break' property inside jQuery that .each() could
catch to break the loop.
Exception based (ala prototype) implementation:
Example:
$("p").each(function() {
if ($(this).is(".unnecessary.beyond.here")) throw $['break'];
$(this).addClass('this').addClass('was').addClass('totally').addClass('required');
};
Code:
jQuery['break'] = new Object();
jQuery.extend({
each: function( obj, fn, args ) {
if ( obj.length == undefined )
for ( var i in obj )
try {
fn.apply( obj[i], args || [i, obj[i]] );
} catch (e) {
if (e == jQuery['break']) break;
throw e;
}
else
for ( var i = 0; i < obj.length; i++ )
try {
fn.apply( obj[i], args || [i, obj[i]] );
} catch(e) {
if (e == jQuery['break']) break;
throw e;
}
return obj;
},
});
Return Value based implementation:
Example:
$("p").each(function() {
if ($(this).is(".unnecessary.beyond.here")) return $['break'];
$(this).addClass('this').addClass('was').addClass('totally').addClass('required');
};
Code:
jQuery['break'] = new Object();
jQuery.extend({
each: function( obj, fn, args ) {
if ( obj.length == undefined )
for ( var i in obj )
if ( fn.apply( obj[i], args || [i, obj[i]] ) ==
jQuery['break']) break;
else
for ( var i = 0; i < obj.length; i++ )
if ( fn.apply( obj[i], args || [i, obj[i]] ) ==
jQuery['break']) break;
return obj;
},
});
The code for this feature is marginal and it is one of the few things
that I miss from my prototype days. This code is untested and might not
work the way I expect it to, but you get the drift.
-blair
NB It may be better to use something other than 'break' as the variable
name as it's a reserved word and you'd have to use the square bracket
notation any time it is used.
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/