设计模式——为javascript插件组织代码的最佳方式

design patterns - The best way to organize my code for a javascript plugin

本文关键字:代码 方式 最佳 javascript 插件 设计模式      更新时间:2023-09-26

大家好!我看到了一些关于这个主题的有趣帖子,但我认为这是一个非常私人的问题,需要一个定制的答案。所以我问你什么是最好的方法来组织我的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方法添加和加载事件来执行这个method1,我想我的代码可以有一个更好的组织。我想准确地说,我的插件有点小,像200车道的javascript代码,它必须在香草js。在我看来,它是在一个网站的一个页面上使用的,不需要做一个叫做new的原型类。

这取决于你的项目和你想要获得的东西。有几种模式可以帮助你更好地组织和维护代码。
就我个人而言,我使用了多年来让自己感到舒适的模式组合。下面是我的应用程序模块的样板文件:

;(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方法-它不会污染全局命名空间与变量(它只是添加一个对象到主应用程序)。

我用的是这一行的东西。都取决于我需要做什么

(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 ||{}))