组织javascript插件代码的最佳方法

时间:2013-01-21 10:20:21

标签: javascript design-patterns architecture

哦,嗨, 我看到了一些关于这个主题的有趣帖子,但我认为这是一个非常个人化的问题需要定制的答案。所以我问你,为Javascript插件组织我的代码的最佳方法是什么,这需要更加无障碍。

所以我的代码看起来像那样:

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

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

我执行调用或使用我的应用程序的整个代码的method1。 我想我可以用addEventListener方法添加和加载事件来执行这个方法1,我猜我的代码可以有一个更好的组织。 我想要确切地知道我的插件有点小,比如200个javascript代码,它必须在Vanilla js中。它在网站的单个页面上使用,在我看来,不需要使用“new”调用原型类。

2 个答案:

答案 0 :(得分: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 :(得分: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 ||{}))
相关问题