简体   繁体   English

如何使用getter方法实现jQuery插件?

[英]How implement a jQuery plugin with a getter method?

I'm starting creating my custom jQuery plugin to manage tags. 我开始创建我的自定义jQuery插件来管理标签。 I'm using an approach based on this patter https://github.com/zenorocha/jquery-plugin-patterns/blob/master/patterns/jquery.basic.plugin-boilerplate.js and all the methods maintains chainability. 我正在使用基于此模式的方法https://github.com/zenorocha/jquery-plugin-patterns/blob/master/patterns/jquery.basic.plugin-boilerplate.js ,所有方法都保持可链接性。

What I would like is to create a method similar to $.css() which allows to set or get values. 我想要创建一个类似于$ .css()的方法,该方法允许设置或获取值。 I have implemented a 'tags' method that adds new tags or, if the passed arguments are undefined it returns an array: 我已经实现了添加新标签的“标签”方法,或者,如果传递的参数未定义,它将返回一个数组:

$(elem).tagger('tags', 'some, tags, here'); // To add more tags
$(elem).tagger('tags');  // This doesnt works because chainability

The second call doesn't works and simply return me an array with the selected elements in the selector (because the chainability mode). 第二个调用不起作用,仅向我返回一个在选择器中具有所选元素的数组(因为可链接性模式)。

How can I implement the getter method? 如何实现getter方法?

Thanks. 谢谢。

ok, I think I found a solution to my problem. 好的,我想我找到了解决问题的方法。 The code is next. 代码是下一个。

I differentiate three possibilities: 我区分三种可能性:

  • Plugin must be created and initialized. 必须创建和初始化插件。
  • A plugin's method is invoked. 插件的方法被调用。
  • A plugin's method, marked as getter, is invoked. 调用标记为getter的插件方法。 In this case I break the chainability and return the methods results. 在这种情况下,我打破了可链接性并返回了方法的结果。

This is my first jQuery plugin. 这是我的第一个jQuery插件。 Could anybody answer me if this is a decent or bad solution? 如果这是一个不错的解决方案,有人可以回答我吗? Thanks in advance. 提前致谢。

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'];

Without seeing your plugin code, I can only offer the following mock code as an answer: 在没有看到您的插件代码的情况下,我只能提供以下模拟代码作为答案:

$.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
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM