Reputation: 674
I am trying to develop plugin using jquery-boilerplate-v3.1 and confused between "this" and "$(this)"
in the plugin
...
$.fn[pluginName] = function ( options ) {
//alert($(this).toSource());
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
}
});
};
seems that the new Plugin(this, options)
does not return the element inside Plugin.prototype context.
Instead, I've modified it to Plugin($(this), options)
.
eg.
$(function(){
$('#container').myPlugin();
});
without using $(this) as parameter, I cannot access this.element in the plugin, .toSource() return empty object ({})
.
Am I doing the correct way by modifying to $(this) or how can I access the #container with this
parameter.
TIA.
Upvotes: 1
Views: 258
Reputation: 700362
In the plugin, this
refers to the jQuery object that you apply the plugin to, but inside the callback for this.each()
, this
refers to each single DOM element inside the jQuery object.
So, yes, you need $(this)
to get a jQuery object containing that element inside the loop.
Upvotes: 2