2013-01-21 47 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 ||{})) 
相关问题