2013-05-29 59 views
2

我正在創建一個jQuery插件,並希望提供若干擴展,以使解決方案更加模塊化。我想我已經得到了正確的語法來執行擴展,但我似乎無法調用我的擴展中的任何方法。我只包含代碼的一部分來嘗試和簡短,但如果需要,我可以提供更多內容。任何幫助深表感謝!在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); 

回答

0

我沒有看到你的代碼的任何地方,你支持調用插件的方法,無論是內置還是後期添加的擴展方法。

如果目的是爲了能夠調用$(el).workflowEditor('mymethod', ...)以同樣的方式爲jQuery UI的工作,那麼也許你需要:

$.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({ ... })(即以對象作爲參數),那麼它將像以前那樣關聯該插件。

+0

謝謝,與其他一些我認爲我已經得到了一些工作的骨頭。看着jQuery UI的幫助。基本上我只是試圖在不同的文件中分開我的插件,以避免一個巨大的100,000行javascript文件。 – Mark

+0

@Mark應該可行,但不要忘記,您不能在代碼模塊之間共享詞典範圍(「私有」)變量。 – Alnitak