views:

321

answers:

4

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.

+7  A: 

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.

Felix Kling
Of course! Thanks, I guess I just took that for granted everytime I have used plugins previously.
Corey Sunwold
While this is absolutely true, the actual reason to `return` it is to allow chaining...
Mef
@Mef: Well I thought this is clear and it is more about why using `each`.
Felix Kling
+3  A: 

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.

Max Toro
+2  A: 

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.

gnarf
A: 

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/

adardesign