使jQuery Boilerplate支持链接

时间:2015-06-17 04:37:57

标签: jquery

根据jQuery Boilerplate page

  

这个 没有 支持链,看起来(原文如此)就像没有那么多人   使用插件链语法。

如何改变它呢?代码是:

/*
 *  Project:
 *  Description:
 *  Author:
 *  License:
 */

// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ($, window, document, undefined) {

    // undefined is used here as the undefined global variable in ECMAScript 3 is
    // mutable (ie. it can be changed by someone else). undefined isn't really being
    // passed in so we can ensure the value of it is truly undefined. In ES5, undefined
    // can no longer be modified.

    // window is passed through as local variable rather than global
    // as this (slightly) quickens the resolution process and can be more efficiently
    // minified (especially when both are regularly referenced in your plugin).

    var // plugin name
        pluginName = "pluginName",
        // key using in $.data()
        dataKey = "plugin_" + pluginName;

    var privateMethod = function () {
        // ...
    };

    var Plugin = function (element, options) {
        this.element = element;

        this.options = {
            // default options
        };

        /*
         * Initialization
         */

        this.init(options);
    };

    Plugin.prototype = {
        // initialize options
        init: function (options) {
            $.extend(this.options, options);

            /*
             * Update plugin for options
             */
        },

        publicMethod: function () {
            // ...
        }
    };

    /*
     * Plugin wrapper, preventing against multiple instantiations and
     * return plugin instance.
     */
    $.fn[pluginName] = function (options) {

        var plugin = this.data(dataKey);

        // has plugin instantiated ?
        if (plugin instanceof Plugin) {
            // if have options arguments, call plugin.init() again
            if (typeof options !== 'undefined') {
                plugin.init(options);
            }
        } else {
            plugin = new Plugin(this, options);
            this.data(dataKey, plugin);
        }

        return plugin;
    };

}(jQuery, window, document));

您目前无法做的事情就像$('div').plugin().css('border', '1px solid red');添加jQuery函数会破坏它。为什么不会一个插件想要支持链接以及如何调整它以支持链接?

1 个答案:

答案 0 :(得分:2)

而不是最后返回plugin,您只需返回this

您可能不想支持链接,因此您可以返回插件的界面,例如

var coolPlugin = $('img').coolPlugin()

coolPlugin.play(500)

大多数插件使用的替代方案,非常难看但有效,类似于coolPlugin('play', 500)