Another way to handle this situation, which is useful if you want to call your plugin s methods from elsewhere (perhaps a different file etc.) is to write the plugin logic as a class and then instantiate that class inside the jQuery plugin, storing the instance in $.data
.
(function($) {
var Animal = function(el, settings) {
this.$el = $(el);
this.settings = settings;
this.foo();
};
Animal.prototype.eat = function() {
// Do stuff
if (this.settings.isVegetarian) {
console.log( I eat plants );
} else {
console.log( I eat meat );
}
};
Animal.prototype.play = function() {
// Do other stuff but return this.$el so you can maintain chain
return this.$el;
};
// Create jQuery plugin
var pluginName = myPlugin ;
$.fn[pluginName] = function(options) {
// Defaults
var settings = $.extend({
isVegetarian: true,
}, options );
return this.each(function() {
if (!$.data(this, pluginName)) {
// Store plugin instace with element (this),
// so public methods can be called later:
// $( .el ).data( myPlugin ).eat();
$.data(this, pluginName, new Animal(this, settings));
}
});
};
}(jQuery));
Then when you want to call your plugin, it s just like normal:
$( .dog).myPlugin();
and call a method:
$( .dog ).data( myPlugin ).eat();