我正在尝试了解与jQuery一起使用的JS模块模式。我已经对此进行了几次编辑,并将尝试以我的技能水平进行良好的练习(在jQuery上几个月)。

这篇文章没有直接的问题。我的目标是在大型网站中正确使用模块模式(与jQuery一起使用)的反馈和输入。

更新: :我添加了许多示例,以获取所有写作方式的概述,并尝试掩盖任何陷阱。

/* 
Not all browsers works with console.log, so we want to make sure that
console.log is defined. This defines the consol.log and send the messages
into an alert.
*/
if(!window.console) console = {
  log: function(s) { 
    alert(s); // alert since we dont have the firebug console
  }
};

// Check if namespace is defined
if (typeof (CompanyName) === 'undefined') {
    CompanyName = {};
}

// Or if AppName under CompanyName...

if (typeof (CompanyName.AppName) === 'undefined') {
    CompanyName.AppName = {};
}

// Our namespace
CompanyName.AppName = (function ($) {

    // CHAINING
    var _first = function () {
        // Important to always start with "var"
    },

    _second = function () {
        // Chained (  ...},  ) so it doesnt need "var"
    },

    _third = "Just a var", // Variables just ends with ,

    _four = "Another var"; // Closing the chain with ;

    var _anotherFirst = function () {
        // Previous chain of var's was ended with ; so this var needed "var" in order to start.
    };

    g_globalVar = "I'm free!"; // When starting a var without "var", it becomes global.

    g_globalMethod = function () { 
        alert("I'm free too!"); // Global method.
    };

    g_chainedGlobalVarOne = "We are free!",
    g_chainedGlobalVarTwo = "We are free!";

    // Private Variables
    var _privateVar = "privateVar: accessed from within AppLaunch.Admin namespace";

    // Private Methods
    var _privateMethod = function () {
       log("privateMethod: accessed only from within AppLaunch.Admin");
    }; // Last variable in a chain must always end with ; before the return {}

    function log() {
        if (window.console && window.console.log)
            window.console.log('[AppName] ' + Array.prototype.join.call(arguments, ' '));
    };

    return {
        init: function () {

            // Calling private
            _privateMethod();

            // Calling Public
            this.myPublicMethod();

            // Also Calling Public
            CompanyName.AppName.myPublicMethod();

            // Calling Other namespace's Public Method (when exists)
            CompanyName.OtherNamespace.externalPublicMethod(); 
        },

        // Public
        myPublicMethod: function() {
            log("myPublicMethod");
        },
        // In a View (MVC), I could have a page called myPage where I want to init
        // some particular functions. myPage can be called just like init. 
        myPage: function() { 
            _second();
            _third();
        }

    }
})(jQuery); 

// Initialize
jQuery().ready(function() {
    CompanyName.AppName.init()
    CompanyName.AppName.myPublicMethod();
});  

试图了解正在发生的事情(随时提供更正或更好的解释):

Company.AppName = (function ($) { ...

在这里,命名空间company.AppName是创建的。我将($)设置在内部,以便我可以使用$而不会与其他可能使用$的库相冲突。

})(jQuery); 

据我所知,方法和变量在此处返回到名称空间...})();通过添加jQuery inside(),它将告诉它$表示jQuery。

初始化

我不确定这里的最佳练习是什么,但是我会添加到目前为止所知道的。

在JS文件中初始化:

jQuery(function() { 
    AppLaunch.Admin.init();
});

从文件初始化:

<script type="text/javascript">
// Shorthand for jQuery(document).ready(function() { ... }

jQuery(function($) { 
    AppLaunch.Admin.init($('#someSelector'));     
});
</script>
有帮助吗?

解决方案

有很多地方可以深入地解释模块模式。 jQuery的用法是非常标准的。

这只是众多 模块模式解释.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top