好的,我想我找到了解决问题的方法。接下来是代码。
我区分了三种可能性:
- 必须创建和初始化插件。
- 调用插件的方法。
- 调用标记为 getter 的插件方法。在这种情况下,我打破了可链接性并返回方法结果。
这是我的第一个 jQuery 插件。如果这是一个不错的或不好的解决方案,有人可以回答我吗?提前致谢。
var pluginName = 'tagger';
//
// Plugin wrapper around the constructor,
// preventing against multiple instantiations and allowing any
// public function (whose name doesn't start with an underscore) to be
// called via the jQuery plugin:
// e.g. $(element).defaultPluginName('functionName', arg1, arg2)
//
$.fn[pluginName] = function(options) {
var args = arguments;
if (options === undefined || typeof options === 'object') {
// Create a plugin instance for each selected element.
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
} else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
// Call a pluguin method for each selected element.
if (Array.prototype.slice.call(args, 1).length == 0 && $.inArray(options, $.fn[pluginName].getters) != -1) {
// If the user does not pass any arguments and the method allows to
// work as a getter then break the chainability
var instance = $.data(this[0], 'plugin_' + pluginName);
return instance[options].apply(instance, Array.prototype.slice.call(args, 1));
} else {
// Invoke the speficied method on each selected element
return this.each(function() {
var instance = $.data(this, 'plugin_' + pluginName);
if (instance instanceof Plugin && typeof instance[options] === 'function') {
instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
});
}
}
};
//
// Names of the pluguin methods that can act as a getter method.
//
$.fn[pluginName].getters = ['tags'];