-
-
Save Striker21/1352993 to your computer and use it in GitHub Desktop.
// $.quickEach() replicates the functionality of $.each() but allows 'this' | |
// to be used as a jQuery object without the need to wrap it using '$(this)'. | |
// The performance boost comes from internally recycling a single jQuery | |
// object instead of wrapping each iteration in a brand new one. | |
// Development ----------------------------------- | |
(function($) | |
{ | |
$.fn.quickEach = function(f) | |
{ | |
var j = $([0]), i = -1, l = this.length, c; | |
while( | |
++i < l | |
&& (c = j[0] = this[i]) | |
&& f.call(j, i, c) !== false | |
); | |
return this; | |
}; | |
})(jQuery); | |
// Minified -------------------------------------- | |
(function($){$.fn.quickEach=function(f){var j=$([0]),i=-1,l=this.length,c;while(++i<l&&(c=j[0]=this[i])&&f.call(j,i,c)!==false);return this}})(jQuery); | |
// Usage ----------------------------------------- | |
(function($) | |
{ | |
$('div').quickEach(function(i, el) | |
{ | |
//'this' is a jQuery object | |
//'i' is the index | |
//'el' is the DOM element | |
//Print the index of each element | |
this.html('Index: '+i); | |
}); | |
})(jQuery); |
Yeah, but when you'll need your reference later, you still will be forced to wrap it into jQuery. Which, actually wraps our element twice (or one and a half), while in .each() it wraps it once only - right?.
But, again, I like your point, that we shouldn't reference to the jQuery object, but to the element itself. Meaning if we need to iterate a collection fast - we use .quickEach without actually wrapping each element. If we'll need any element later - we'll wrap it manually. Thanks for that tip :)
You are correct. If you plan on referencing one of the objects again you will need to wrap it if you plan on using jQuery functions on it. In that scenario, you may be better off using standard $.each().
However, if you're storing a reference to the entire collection, then quickEach is still the better option. This is what you'd do:
var myCollection = $('div'); //You now have a variable referencing all of the divs
myCollection.quickEach(function(i, e)
{
/* Do stuff */
});
//Later on, do stuff to the same collection
myCollection.quickEach(function(i, e)
{
/* Do more stuff */
});
/* Do even more stuff */
myCollection.addClass('foo');
No, there is no way around that problem because you're saving a reference to the jQuery object which is recycled for every iteration. The solution would be not to save a reference to the jQuery object, but to the element's node.
This can be done two ways, which I've combined into one code snippet