2011-01-29 87 views
6

如何管理定製JavaScript庫的命名空間取決於jQuery?帶jQuery的JavaScript命名空間

您是否創建自己的名稱空間,例如foo並在其中添加對象?例如foo.myClass, foo.myFunction

或者您是否將對象添加到jQuery的名稱空間?例如jQuery.myClass, jQuery.myFunction

哪一種更常見的做法,爲什麼?

+1

LOL不要你的屬性添加到jQuerys命名空間... – 2011-01-29 19:13:09

+1

潛入RequireJS非jQuery插件管理;) – BGerrissen 2011-01-29 19:34:28

回答

4

這取決於圖書館的功能。

  • 如果您正在擴展的jQuery對象實例的功能,你會使用jQuery.fnhis answer被形容非常漂亮的@David Titarenco

  • 如果您正在創建的實用程序被認爲是window.jQuery中提供的實用程序的附件,那麼使用該命名空間時不會出現問題(只要您小心命名)。

  • 如果真的是自己單獨的庫,意味着被視爲jQuery的的延伸,但依賴於從jQuery的功能,那麼肯定使用自己的名稱空間。

7

This article討論編寫jQuery插件/庫在極其詳盡的細節。

什麼不該做的事:

(function($){ 

    $.fn.tooltip = function(options) { // THIS }; 
    $.fn.tooltipShow = function() { // IS }; 
    $.fn.tooltipHide = function() { // BAD }; 
    $.fn.tooltipUpdate = function(content) { // !!! }; 

})(jQuery); 

怎麼辦:

(function($){ 

    var methods = { 
    init : function(options) { // THIS }, 
    show : function() { // IS }, 
    hide : function() { // GOOD }, 
    update : function(content) { // !!! } 
    }; 

    $.fn.tooltip = function(method) { 

    // Method calling logic 
    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.tooltip'); 
    }  

    }; 

})(jQuery); 

我也blog post去年寫了一篇關於各種方法在JavaScript命名空間(非jquery相關)。