开发者

Why return this.each(function()) in jQuery plugins?

Some of the tutorials and开发者_运维技巧 examples I have seen for developing jQuery plugins tend to return

this.each(function () {
    //Plugin code here
});

at the end of the function that instantiates the plugin but I have yet to see any reasoning behind it, it just seems to be a standard that everyone follows. Can anyone enlighten me as to the reasoning behind this practice?

Edit: For clarification my question was not about why to return this, but rather why the plugin should return this.each.


When you filter elements with a selector ($('.myclass')), it can match more than only one element.
With each, you iterate over all matched elements and your code is applied to all of them.


jQuery supports "chainable methods", which means that most jQuery functions should return this. .each() returns this, and if you want $('selector').yourPlugin().css(...) to work, you should return this.


Let me show you two "equivalent" pieces of code that could clarify your question:

With jQuery "each" function:

(function($) {
    $.fn.mangle = function(options) {
        return this.each(function() {
            $(this).append(' - ' + $(this).data('x'));
        });
    };
})(jQuery);

Without jQuery "each" function:

(function($) {
    $.fn.mangle = function(options) {
        var objs = this;
        for (var i=0; i<objs.length; i++) {
            var obj = objs[i];
            $(obj).append(' - ' + $(obj).data('x'));
        };
        return this;
    };
})(jQuery);

So, basically, each function is used to apply some code to all elements contained in this object (as this usually refers to a group of elements returned by a jQuery selector) and return the reference to this (as each function always returns that reference -to allow chaining calls-)

As a side note: The second approach (-for loop-) is faster (notably on old browsers) than former one (-each function-).


When you write a plugin you are extending the jQuery object, and because the jQuery object is a sequence you return this.each(function () { }); so that your plugin is executed for each item of the sequence.


In short it allows you to take advantage of chaining, since it returns everything that has been done till now so the next .anyMethod() can act upon the changed/modified elements.



Additionally, take a look at these links they will give you a lot of information on jQuery plugin development.

http://www.webresourcesdepot.com/jquery-plugin-development-10-tutorials-to-get-started/
http://www.learningjquery.com/2007/10/a-plugin-development-pattern
http://snook.ca/archives/javascript/jquery_plugin

And here you have a nice web based app that helps you jump start your jQuery plugins. http://starter.pixelgraphics.us/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜