我如何为这个jQuery插件模式添加一个方法?

时间:2012-06-11 10:06:54

标签: jquery plugins

我正在使用以下代码作为我正在为项目工作的插件的基础 - 这是来自Smashing Magazine的一篇文章,位于“轻量级开始”标题下:

http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/

到目前为止,它一直在我的目的下工作正常,但本文的其余部分是关于切线并讨论jQuery UI小部件,我认为我需要jQuery UI库,我真的不想要使用。

/*!
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, comments: @addyosmani
 * Licensed under the MIT license
 */

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

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

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

    // Create the defaults once
    var pluginName = 'defaultPluginName',
        defaults = {
            propertyName: "value"
        };

    // The actual plugin constructor
    function Plugin( element, options ) {
        this.element = element;

        // jQuery has an extend method that merges the
        // contents of two or more objects, storing the
        // result in the first object. The first object
        // is generally empty because we don't want to alter
        // the default options for future instances of the plugin
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Plugin.prototype.init = function () {
        // Place initialization logic here
        // You already have access to the DOM element and
        // the options via the instance, e.g. this.element
        // and this.options
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                new Plugin( this, options ));
            }
        });
    }

})( jQuery, window, document );

我现在需要为此添加一个方法,但我对如何操作非常无能为力。

该方法需要以这样的方式工作:插件在页面上创建的实例可以通过控制台调用带有值的方法来动态更改属性(最终这将通过其他一些进程发生,但控制台现在很好用。)

我如何修改上面的代码以实现此目的?还是我在错误的树上吠叫?

任何帮助都会受到高度赞赏,复杂的JavaScript可能会让我在黑暗中有点迷失,但有时我会尽量做“最佳实践”。

3 个答案:

答案 0 :(得分:12)

jQuery文档强烈建议通过将字符串传递给主插件方法来调用插件方法。这是为了阻止$.fn命名空间被插件的方法弄得乱七八糟。所以你做这样的事情:

$.fn.yourPlugin = function(options) {
    if (typeof options === "string") {
        //Call method referred to by 'options'
    } else {
        //Setup plugin as usual
    }
};

在您的模式中,您已经拥有了定义方法的最佳位置:Plugin.prototype。例如,要添加changeColor方法:

Plugin.prototype.changeColor = function(color) {
    $(this.element).css("color", color);
}

请注意$(this.element)的使用。这是因为在Plugin构造函数中,定义了属性element,并且为其分配了应用插件的元素:

this.element = element;

这是实际的DOM元素,而不是jQuery对象,因此需要在其上调用jQuery。

所以现在你有了一个方法,你需要添加一个机制来调用它。遵循jQuery文档的建议:

$.fn[pluginName] = function ( options ) {
    return this.each(function () {
        if (typeof options === "string") {
            var args = Array.prototype.slice.call(arguments, 1),
                plugin = $.data(this, 'plugin_' + pluginName);
            plugin[options].apply(plugin, args);
        } else if (!$.data(this, 'plugin_' + pluginName)) {
            $.data(this, 'plugin_' + pluginName,
            new Plugin( this, options ));
        }
    });
};

然后您可以像这样调用changeColor方法:

$("#example").defaultPluginName("changeColour", "red");​​​​​​​​​​​​​​​​​​​​​​​​​​​

这里是fiddle with a working example。您可能希望在方法调用代码周围添加一些检查,以确保插件实际上已在您调用它的元素上实例化。

答案 1 :(得分:0)

使用

Plugin.prototype.reset = function () {

};
Plugin.prototype.destroy = function () {

};

等等。添加任意数量的选项

答案 2 :(得分:0)

不是从难以理解的样板开始,而是从最初的起点开始:

http://docs.jquery.com/Plugins/Authoring