jQuery插件从方法返回值,仍然保持可链接性

时间:2012-12-23 15:05:51

标签: jquery jquery-plugins return-value chaining

我目前正在重新设计我的个人jQuery插件的起点,但我遇到了一个小问题。如果调用了一个公共方法,它将返回调用它的对象,而不是值。

这是我开始的实际观点:

;(function($, window, document, undefined) {
    'use strict';

    var pluginName = 'defaultPluginName',
        defaults = {
            foo: 'foo',
            bar: 'bar'
        },
        settingsKey = pluginName + '-settings';


    var init = function(options) {

        var elem = this,
            $elem = $(this),
            settings = $.extend({}, defaults, options);

        $elem.data(settingsKey, settings);

    };


    var callMethod = function(method, options) {
        var methodFn = $[pluginName].addMethod[method],
            args = Array.prototype.slice.call(arguments);
        if (methodFn) {
            this.each(function() {
                var opts = args.slice(1),
                    settings = $(this).data(settingsKey);
                opts.unshift(settings);
                methodFn.apply(this, opts);
            });
        }
    };

    $[pluginName] = {
        settingsKey: settingsKey,
        addMethod: {
            option: function(settings, key, val) {
                if (val) {
                    settings[key] = val;
                } else if (key) {
                    return settings[key]; // returns the value from settings
                }
            }
        }
    };

    $.fn[pluginName] = function(options) {
        if (typeof options === 'string') {
            callMethod.apply(this, arguments);
        } else {
            init.call(this, options);
        }
        return this;
    };

}(window.jQuery || window.Zepto, window, document));

但是,我初始化插件并调用方法...

$('div').defaultPluginName();
console.log($('div').defaultPluginName('option', 'foo'));

它返回:[<div>, <div>, prevObject: jQuery.fn.jQuery.init[1], context: #document, selector: "div"]而不是'foo'(从评论所在位置除外)。

所以问题是,是否可以从公共方法返回值并仍然保持可链接性?如果你有时间和乐趣来帮助我,我会很高兴看到一些例子;)

1 个答案:

答案 0 :(得分:1)

我自己解决了这个问题:

$.fn[pluginName] = function(options) {
    var returns;
    if (typeof options === 'string') {
        var args = arguments,
            methodFn = $[pluginName].addMethod[args[0]];

        if (methodFn) {
            this.each(function() {
                var opts = Array.prototype.slice.call(args, 1),
                    settings = $.data(this, settingsKey);
                opts.unshift(settings);
                returns = methodFn.apply(this, opts);
            });
        }
    } else {
        new Plugin(this, options).init();
    }
   return returns !== undefined ? returns : this;
};