另一种处理这种情况的方法,如果您想从其他地方(可能是不同的文件等)调用插件的方法,这很有用,是将插件逻辑编写为一个类,然后在 jQuery 插件中实例化该类,存储实例在$.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));
然后当你想调用你的插件时,就像平常一样:
$('.dog).myPlugin();
并调用一个方法:
$('.dog').data('myPlugin').eat();