2014-02-11 58 views
0

我最喜歡的設計模式來創建一個jQuery插件如下所示。在jquery插件中需要命名空間嗎?

是否有任何理由爲插件中的方法創建名稱空間?具體來說,我使用下面顯示的var privateMethods

(function($){ 
    var privateMethods={}; 
    privateMethods.method1=function(){alert('privateMethods1');}; 
    privateMethods.method2=function(){alert('privateMethods2');}; 
    privateMethods.method3=function(){alert('privateMethods3');}; 

    var privateMethod1=function(){alert('privateMethods1');}; 
    var privateMethod2=function(){alert('privateMethods2');}; 
    var privateMethod3=function(){alert('privateMethods3');}; 

    function privateFunction1(){ 
     //Consider using this approach if there is significant script 
     alert('privateFunction1'); 
    } 

    var defaults = { //private, right? 
     foo: 'bar' 
    }; 

    var methods = { 
     init : function (options) { 
      var settings = $.extend({}, defaults, options); 
      return this.each(function() { 
       //do whatever 
      }); 
     }, 
     destroy : function() { 
      return this.each(function() {}); 
     }, 
     otherPublicMethod : function() { 
      return $(this).each(function(){ 
       //do whatever 
      }) 
     } 
    }; 

    $.fn.myPlugin = function(method) { 
     if (methods[method]) { 
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
     } else if (typeof method === 'object' || ! method) { 
      return methods.init.apply(this, arguments); 
     } else { 
      $.error('Method ' + method + ' does not exist on jQuery.myPlugin'); 
     }  
    }; 
    }(jQuery) 
); 
+0

是的,如果你希望第三方開發者能夠擴展你的插件以適應他們的需求,那麼他們有一個特殊的用例。我會使該名稱空間可用,以便可以根據需要對其進行擴展/重寫。例如''。$ .fn.myPlugin.privateMethods = {}'。 –

+0

@KevinB我需要做什麼比我爲'privateMethods'顯示使其可用嗎? – user1032531

+0

是的,因爲目前覆蓋/擴展它的唯一方法是直接編輯js。最後'$ .fn.myPlugin._ = privateMethods'就足夠了。 ''方法'可以做同樣的事情。 –

回答

0

關於之外你的插件範圍的方法的可見性有

  • privateMethods.method
  • privateMethod1 = function(){}
  • function privateFunction(){}

之間沒有差異。另一方面命名空間不有任何嚴重的缺陷ap藝術從你的jQuery插件將會有的稍微大一些(可以輕鬆地通過縮小和縮小代碼來緩解)。可能的優點是有可能:

  • 打破你的方法將命名空間組
  • 使用知名圍繞命名空間的Javascript模式,使您的代碼可讀性和可維護性,如引進一個邏輯結構代碼:http://addyosmani.com/blog/essential-js-namespacing/
  • 封裝。獲取與具有海量代碼庫的插件相關

結論:總體而言,我會選擇隨時使用名稱空間。