Reputation: 2983
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
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
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