Tuesday, April 17, 2012

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.


Source: Tips4all

4 comments:

  1. 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.

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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.

    ReplyDelete
  4. 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/

    ReplyDelete