Reputation: 119847
i'm currently exploring jQuery's plugin authoring and:
var methods = {
init : function(options) {
console.log(options);
return this.each(function() {
console.log(options);
});
}
};
the tutorial said that to maintain chainability (which i may use), i should return this.each()
. i see that calling $('div').myPlugin({'test':'test'})
calls the init function and logs in the console options
. however, i don't seem to see options
inside return this.each()
.
can someone explain why is that so? is this normal behavior?
Upvotes: 0
Views: 137
Reputation: 16544
The .each() method of jQuery has a pre-defined set of parameters, so the first parameter will be treated as the index of the current element. So "options" will be replaced with the index. There is no need to hand-over "options" to the function, though, it will be automatically available as the function creates a closure.
return this.each(function() {
console.log(options);
});
Hint: You are not actually returning this.each() ... technically you are just returning "this"
Upvotes: 2