Created
July 30, 2010 08:25
-
-
Save padolsey/500145 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The `quickEach` method will pass a non-unique jQuery instance | |
// to the callback meaning that there will be no need to instantiate | |
// a fresh jQuery instance on each iteration. Most of the slow-down | |
// inherent in jQuery's native iterator method (`each`) is the constant | |
// need to have access to jQuery's methods, and so most developers | |
// see constructing multiple instances as no issue... E.g. | |
// $(...).each(function(){ $(this)... $(this)... $(this)... }); | |
// A better approach would be `quickEach`. | |
jQuery.fn.quickEach = (function(){ | |
var jq = jQuery([1]); | |
return function(c) { | |
var i = -1, el, len = this.length; | |
try { | |
while ( | |
++i < len && | |
(el = jq[0] = this[i]) && | |
c.call(jq, i, el) !== false | |
); | |
} catch(e){ | |
delete jq[0]; | |
throw e; | |
} | |
delete jq[0]; | |
return this; | |
}; | |
}()); | |
// E.g. | |
jQuery('div').quickEach(function(i){ | |
// `this` is a jQuery object | |
this.attr('id', 'd' + i).css('color', 'red'); // etc. | |
}); |
Just something helpfull: jQuery.fn.each = jQuery.fn.quickEach || jQuery.fn.each2 || jQuery.fn.each;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use a
try/finally
instead of atry/catch
and a doubledelete jq[0]
.