您应该防止在 jQuery 样板方法中重新初始化:
(function($) {
var PLUGIN_IDENTIFIER = "my-plugin";
...plugin definition etc
//jQuery boilerplate
$.fn.myPlugin = function(opts) {
return this.each(function() {
var instance = $(this).data(PLUGIN_IDENTIFIER);
//Prevent reinit on this element
if (!instance) {
instance = new MyPlugin(this, opts);
$(this).data(PLUGIN_IDENTIFIER, instance);
}
//Method call
if (typeof opts === "string") {
instance[opts].apply(instance, [].slice.call(arguments, 1));
}
});
};
})();
您应该始终提供一种"destroy"
方法来删除它添加的 .data 和事件侦听器。所以只能在调用后重新初始化,"destroy"
这也方便地删除了事件侦听器。
这是一个非常标准的销毁方法的示例实现:
function MyPlugin(element, opts) {
this.element = $(element);
this.opts = $.extend(defaults, $(element).data(), opts);
//Other instance state
//absolutely do not use $.data for this, you should only occupy one $.data
//slot for your plugin for the same reason you only occupy one slot on
//$.fn
}
MyPlugin.prototype.destroy = function() {
this.element.removeData(PLUGIN_IDENTIFIER);
this.element.off(".myplugin"); //Remove all events off the element that belong to the plugin's namespace
//.remove() any helper elements created by the plugin
this.element = null;
};