在jQuery扩展中调用方法

时间:2013-05-29 15:19:52

标签: jquery jquery-plugins

我正在创建一个jQuery插件,并希望通过更加模块化的解决方案提供几个扩展。我想我已经有了正确的语法来执行扩展,但我似乎无法调用扩展中的任何方法。我只是包含了代码的各个部分,试着简短但我可以提供更多,如果需要的话。非常感谢任何帮助!

我正在使用http://jqueryboilerplate.com/作为我的主插件,以及用于添加扩展程序的stackoverflow答案:Best Way to Extend a jQuery Plugin

主jQuery插件

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

    // jQuery has an extend method which merges the contents of two or
    // more objects, storing the result in the first object. The first object
    // is generally empty as 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() {

        //This line does NOT work
        var id = this.showId();
        console.log(id);

        var toolbar = this.createToolbar(this.options);
        $(this.element).append(toolbar);

        if(this.options.showPalette)
        {
            var palette = this.createPalette(this.options);
            $(this.element).append(palette);
            this.fetchPalette();
        }

        var canvas = this.createCanvas(this.options);
        $(this.element).append(canvas);

    }, .... 

插件构造函数

$.fn[pluginName] = function ( options ) {
    return this.each(function () {
        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName, new Plugin( this, options ));
        }
    });
};

扩展方法

var extensionMethods = {
    /*
     * retrieve the id of the element
     * this is some context within the existing plugin
     */
    showId: function(){
        return this.element[0].id;
    }, ....

jQuery扩展

$.extend(true, $['fn']['workflowEditor'].prototype, extensionMethods);

1 个答案:

答案 0 :(得分:0)

我没有在您的代码中看到您支持调用插件方法的任何位置,无论是内置的还是稍后添加的扩展方法。

如果意图是能够以与jQuery UI相同的方式调用$(el).workflowEditor('mymethod', ...),那么您可能需要:

$.fn[pluginName] = function (options) {
    var ns = "plugin_" + pluginName;  // don't repeat yourself...
    if (options instanceof object) {
        return this.each(function () {
            if (!$.data(this, ns)) {
                $.data(this, ns, new Plugin( this, options ));
            }
        });
     } else {
         var args = [].slice.call(arguments, 0);  // copy args
         var method = args.shift();
         return this.each(function() {
             $['fn'][pluginName][method].apply($.data(this, ns), args);
         });
     }
};

应该调用Plugin.method,上下文是保留的Plugin对象,参数是参数列表的其余部分。

如果被称为$(el).workflowEditor({ ... })(即以对象作为参数),那么它将像以前一样关联插件。