Otra manera de manejar esta situación, que es útil si desea llamar a los métodos de su plugin desde otro lugar (tal vez un archivo, etc. diferente) es escribir la lógica de complemento como una clase y luego una instancia de esa clase en el interior el complemento jQuery, que almacena la instancia en $.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));
Entonces, cuando usted quiere llamar a su complemento, es sólo como normal:
$('.dog).myPlugin();
y llamar a un método:
$('.dog').data('myPlugin').eat();
THX, sencilla y buena solución clara – apelliciari