簡體   English   中英

組織我的JavaScript插件代碼的最佳方法

[英]The best way to organize my code for a javascript plugin

哦,嗨,我看到了一些有關此主題的有趣帖子,但我認為這是一個非常個人化的問題,需要定制的答案。 因此,我想問您什么是最好的組織Java代碼插件代碼的最佳方法?

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

    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”的原型類。

這實際上取決於您的項目以及您想要獲得的東西。 有幾種模式可以幫助您更好地組織和維護代碼。
我曾經使用一種模式組合,這些年來我使自己感到很舒服。
這是我的應用程序模塊的樣板:

;(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方法-而它不會t用變量污染全局名稱空間(它只是將一個對象添加到主應用程序)。

我用這種東西。 一切都在我需要完成的事情上pent悔

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM