了解JS模块模式如何工作 [英] Understanding how JS Module Pattern works

查看:129
本文介绍了了解JS模块模式如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图理解js模块模式与jQuery一起使用。我已经编辑了这几次,并将尝试结束一个良好的练习我的技能水平(几个月新鲜的jquery)。



没有这个帖子中的直接问题。我更希望对大型网站如何正确使用模块模式(与jquery一起)进行反馈和投入。



更新:我已经添加了一些例子,以便了解所有写作方式的概述,并尝试覆盖任何陷阱..

  / * 
并不是所有的浏览器都可以和console.log一起使用,所以我们要确保
console.log被定义。这定义了consol.log并将消息
发送到警报。
* /
if(!window.console)console = {
log:function(s){
alert(s); //警报,因为我们没有firebug控制台
}
};

//检查命名空间是否定义
if(typeof(CompanyName)==='undefined'){
CompanyName = {};
}

//或如果AppName在CompanyName ...

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

//我们的命名空间
CompanyName.AppName =(function($){

// CHAINING
var _first = function (){
//重要的是始终以var开头
},

_second = function(){
//链接(...) )所以它不需要var
},

_third =只是一个var,//变量刚刚结束,

_four =另一个var ; //关闭链;

var _anotherFirst = function(){
//以前链的var结束了;所以这个var需要var才能启动。
};

g_globalVar =我是免费的; //当启动没有var的var时,它变为全局

g_globalMethod = function (){
alert(我也是免费的!); //全局方法
};

g_chainedGlobalVarOne =我们是免费的!
g_chainedGlobalVarTwo =我们是免费的;

//私有变量
var _privateVar = privateVar:从AppLaunch.Admin命名空间中访问

//私有方法
var _privateMethod = function(){
log(privateMethod:仅在AppLaunch.Admin内部访问);
}; //链中的最后一个变量必须始终以...结尾;在返回之前{}

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

return {
init:function(){

//调用private
_privateMethod();

// Calling Public
this.myPublicMethod();

//还调用public
CompanyName.AppName.myPublicMethod();

//调用其他命名空间的公共方法(当存在时)
CompanyName.OtherNamespace.externalPublicMethod();
},

//公开
myPublicMethod:function(){
log(myPublicMethod);
},
//在视图(MVC)中,我可以有一个名为myPage的页面,我想要init
//某些特定的函数。 myPage可以像init一样调用。
myPage:function(){
_second();
_third();
}

}
})(jQuery);

//初始化
jQuery()。ready(function(){
CompanyName.AppName.init()
CompanyName.AppName.myPublicMethod();
});



试图了解发生了什么(随意提供更正或更好的解释):



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

这里创建了命名空间Company.AppName,我设置($)里面,所以我可以使用$,而不与任何其他可能使用$的库冲突。

 })(jQuery); 

据我所知,方法和变量在这里返回到命名空间...}) ();并通过添加jQuery inside()它会告诉它,$ means jQuery。



初始化



我不知道这里最好的做法,但我会添加我所知道的



在js文件中初始化:

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

从文件初始化:

 < script type =text / javascript> 
// jQuery(文件)的速记.ready(function(){...}

jQuery(function($){
AppLaunch.Admin.init '#someSelector'));
});
< / script>


解决方案

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



这只是许多模块模式解释中的一个


I'm trying to understand js module patterns in use with jQuery. I've edited this a couple of times and will try to end up with a good practice for my skill level (a couple of months fresh on jquery).

There's no direct question in this post. I'm more aiming for feedback and inputs on how to properly use the module pattern (together with jquery) in a large scale website.

Update: I've added a bunch of examples in order to get an overview of all ways of writing things, and try to cover any pitfalls..

/* 
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();
});  

Trying to understand what's happening (Feel free to provide corrections or better explanations):

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

Here the namespace Company.AppName is created. I set ($) inside so I can use the $ without it conflicting with any other libraries that might use $.

})(jQuery); 

As far as I know, the methods and variables are returned to the namespace here ...})(); and by adding jQuery inside () it'll tell it that the $ means jQuery.

Initializing

I'm not sure what's best practice here, but I'll add what I know so far.

Initializing within js file:

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

Initializing from a file:

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

jQuery(function($) { 
    AppLaunch.Admin.init($('#someSelector'));     
});
</script>

解决方案

There are many places that will give you an in depth explanation of the module pattern; jQuery's usage of it is pretty standard.

This is just one of the many module pattern explanations out there.

这篇关于了解JS模块模式如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆