我开始创建自定义jQuery插件来管理标签。 我正在使用基于此模式https://github.com/zenorocha/jquery-plugin-patterns/blob/master/patterns/jquery.basic.plugin-boilerplate.js的方法,并且所有方法都保持可链接性。
我想要的是创建一个类似于$ .css()的方法,它允许设置或获取值。 我已经实现了一个添加新标签的'tags'方法,或者,如果传递的参数未定义,则返回一个数组:
$(elem).tagger('tags', 'some, tags, here'); // To add more tags
$(elem).tagger('tags'); // This doesnt works because chainability
第二个调用不起作用,只返回一个包含选择器中所选元素的数组(因为可链接模式)。
如何实现getter方法?
感谢。
答案 0 :(得分:3)
我区分了三种可能性:
这是我的第一个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'];
答案 1 :(得分:2)
如果没有看到您的插件代码,我只能提供以下模拟代码作为答案:
$.fn.myVersatilePlugin = function (options, values) {
if (values === undefined) {
//do something to element with given `values`
return this; // <-- chainability
} else {
values = {};
// do whatever it is you do to get what you want to return
return values; // and return it
}
};