2013-01-21 48 views
0

噢, 我看到一些關於這個主題的有趣帖子,但我認爲這是一個非常個人化的問題,需要一個定製的答案。所以我問你,爲我的Javascript插件組織我的代碼的最佳方式是什麼,這個插件必須是更加不可阻擋的可能。組織我的JavaScript插件代碼的最佳方式

所以我的代碼看起來像這樣:

var myApp = (function(){ 
     //here are my global methods or variables 
     var self = this; 
     return { 
      method1:function(){} 
      method2:function(){} 
      method3:function(){} 
    } 

    })() || (myApp = {}) 
myApp.method1(); 

我執行調用該方法1或使用我的應用程序的全部代碼。 我想我可以使用addEventListener方法添加和加載事件來執行這個方法1,我想我的代碼可以有更好的組織。 我想要確切的說我的插件有點小,就像200碼的javascript代碼,它必須在Vanilla js中。它在網站的單個頁面上使用,在我看來,不需要用「新」來創建一個原型類。

回答

1

這實際上取決於你的項目和你試圖獲得什麼。 有幾種模式可以幫助您更好地組織和維護代碼。
我一個人使用了多年來讓我感覺舒適的模式組合。
這是我爲我的應用程序的模塊樣板:

;(function(global, udnefined){ 

    var app = global.app || {}, 
     moduleName = 'util', 
     module = app[moduleName] || {}; 

    // "private" vars 
    var version = "1.2"; 

    // fake "private" members (the udnerscore naming convention) 
    module._bindEventHandlers = function(){ 
     // code here 

     // for chainability purposes 
     return this; 
    } 

    // "public" method 
    module.someMethod = function(){ 


     // for chainability purposes 
     return this; 
    } 

    // "public" method 
    module.someOtherMethod = function(){ 


     // for chainability purposes 
     return this; 
    } 

    // the init method 
    module.init = function(){ 
     this 
      ._bindEventHandlers() 
      .someMethod(); 
    } 

    app[moduleName] = module; 
    global.app = app; 

})(this); 

,然後在您的應用程序(在應用程序初始化或當你實際需要的模塊),你可以簡單地調用:

app.util.init(); 
app.util.someOtherMethod(); 

所提供模塊是用於創建新的模塊,因爲大多數模塊應該有一個初始化邏輯(init方法)高度可重用,大多會聽的某些事件(無論是DOM或自定義事件) - _bindEventHandlers方法 - 它不會污染具有變量的全局名稱空間(它只是將一個對象添加到主應用程序中)。

1

我使用這件事情的東西。所有依賴我需要做什麼

(function(app, undefined){ 
    var module = app.module = (function(){ 
    var privatestuff 

    return {} 
    }()) 

    var singelton = app.singleton = (function(){ 
    var Module = function(){} 

    module.prototype.method1 = function(){} 

    return new Module() 
    }()) 

    var ModulePrototype = app.ModulePrototype = function(){ 
    var Module = function(){} 

    module.prototype.method1 = function(){} 

    return Module 
    } 
}(myApp = window.myApp ||{})) 
相關問題