Richard Banks
Richard Banks

Reputation: 2983

why use each when creating a jquery plugin

Im a bit confused with the use of each when creating plugins. Ive created a simple plugin with a callback as a test.

<div>Click me 1</div>
<div>Click me 2</div>

Without each :-

(function($){    
    $.fn.TestCallBack = function(options){
        var defaults = {
            onClicked :function(){}
        }

        var settings = $.extend({}, defaults, options); 

        function DoSomething(){
            settings.onClicked.call(this);    
        }

        $(this).bind("click", DoSomething);     

        return this;
}
})(jQuery);

$("div").TestCallBack({onClicked:function(){
    console.log($(this).html());
}});

This produces the results

Click me 1
Click me 2

With each :-

(function ($) {
    $.fn.TestCallBack = function (options) {
        var defaults = {
            onClicked: function () {}
        }

        var settings = $.extend({}, defaults, options);

        function DoSomething() {
            settings.onClicked.call(this);
        }

        this.each(function(){
            $(this).bind("click", DoSomething);
        });        

        return this;
    }
})(jQuery);

$("div").TestCallBack({
    onClicked: function () {
        console.log($(this).html());
    }
});

this produces the results

Click me 1
Click me 2

i thought using each would iterate over the divs found but why does the code not using each provide the same results. Im obviosuly missing something here. Any ideas?

Upvotes: 0

Views: 53

Answers (2)

Abhitalks
Abhitalks

Reputation: 28417

You use each to be able to follow jQuery convention of returning the original set of jQuery objects, which in turn enables chaining.

The way you are using each doesn't make it. It should be used like this:

 $.fn.extend({
        TestCallBack : function () {
            return this.each(function () {
                // write your code here
            });
        }
});

Now you can code like this:

$('div').TestCallBack().stop().show(). .....

Without each returning, you will not be able to chain further jQuery methods on the original set.

More information here: http://learn.jquery.com/plugins/basic-plugin-creation/

Scroll down on that page to the section: "Using the each() Method"

Upvotes: 0

Dennis
Dennis

Reputation: 14485

The only thing you do to this is calling jQuery's bind on it. This internally does that operation for all elements of the set this.

You would need to iterate over all elements with each when doing something with them that is not automatically applied to all items of the set.

Upvotes: 3

Related Questions