JavaScript Modular Programming (note)

Source: Internet
Author: User

Chapter One JavaScript modular programming

(a): How the module is written

A primitive notation
A module is a set of methods to implement a specific function, as long as the different functions (and the variables that record the state) are simply put together, even if it is a module;
function M1 () {
// ...
}
function m2 () {
// ...
}
The above functions M1 () and M2 () to form a module;
Disadvantage: "Pollution" of the global variables; There is no guarantee that the variable name conflicts with other modules, and there is no direct relationship between the module members;

Two-Object notation

1234567891011121314 // 把模块写成一个对象,所有的模块成员都放到这个对象里面;  var module = newObject({    _count:0,    m1:function(){      // ...    },    m2:function(){      // ...    }  });// 上面的函数m1()和m2(),都封装在module对象里;使用时直接调用这个对象的属性;  module.m1();// 但是,这样的写法会暴露所有模块成员,内部状态可以被外部改写;  module._count = 4;

Third, immediately execute the function notation

12345678910111213141516   var module = (function(){    var_count = 0;    varm1 = function(){      // ...    };    var m2 = function(){    };    return{      m1:m1,      m2:m2    };  })();// 使用上面的写法,外部代码无法读取内部的_count变量;  console.info(module._count); // undefined;// 上面的写法就是JavaScript模块的基本写法;

Quad magnification mode

12345678 // 如果模块很大,必须分成几个部分,或者一个模块需要继承另一个模块,这时就有必要采用"放大模式";  varmodule = (function(mod){    mod.m3 = function(){      // ...    };    returnmod;  })(module);// 上面的代码为module模块添加了一个新方法m3(),然后返回新的module模块;

Five-wide magnification mode

1234567 // 在浏览器环境中,模块的各个部分通常都是从网上获取的,有时无法知道哪个部分会先加载;// 如果采用上一节的写法,第一个执行的部分有可能加载一个不存在的空对象,这时就要采用"宽放大模式";  varmodule = (function(mod){    // ...    returnmod;  })(window.module || {});// 与"放大模式"相比,"宽放大模式"就是"立即执行函数"的参数可以是空对象;

Six input global variables

1234567 // 独立性是模块的重要特点,模块内部最好不与程序的其他部分直接交互;// 为了在模块内部调用全局变量,必须显式地将其他变量输入模块;  varmodule = (function($,YAHOO){    // ...  })(jQuery,YAHOO);// 上面的module模块需要使用jQuery库和YUI库,就把这两个库(其实是两个模块)当作参数输入module;// 这样做除了保证模块的独立性,还使得模块之间的依赖关系变得明显;

Chapter II JavaScript modular Programming (II): AMD specifications

Specification of a module
Currently, there are two types of JavaScript module specifications: Commonjs and AMD;

Two CommonJS
node. JS uses the JavaScript language for server-side programming, which marks the formal birth of JavaScript modular programming;
Node. JS's module system is implemented with reference to the COMMONJS specification;
In Commonjs, there is a global method require (), which is used to load modules;
var math = require (' math '); Loading module;
Math.add (2,3); Calling the module method =>5;

Three-browser environment
The previous section of the code running in the browser will have a lot of problems;
var math = require (' math ');
Math.add (2,3);
Problem: The Require (' math ') must be loaded math.js to execute math.add (2,3);
Therefore, the browser module, can not be used "synchronous loading", can only use "Asynchronous loading";==>amd;

Four AMD
AMD (asynchronous module definition) asynchronous module definition;
With the asynchronous load module, the load of the module does not affect the execution of the statement behind it, all statements that depend on the module are defined in a callback function,
The callback function will not run until the load is completed.
AMD also uses the Require () statement to load the module, but it requires two parameters:
Require ([module],callback);
Module: is an array in which the member is the module to be loaded;
Callback: Is the callback function after the successful loading;
Require ([' Math '],function (math) {
Math.add (2,3);
});
Math.add () is not synchronized with the math module, the browser will not be suspended animation; therefore, AMD is more suitable for the browser environment;

Chapter III JavaScript modular Programming (III): Usage of require.js
Why use a Require.js
Need to load multiple JS files sequentially;
Disadvantages:
1. When loading, the browser stops the page rendering, the more files loaded, the longer the webpage loses its response time;
2. Due to the existence of a dependency between JS files, the loading order must be strictly guaranteed, and when the dependencies are complex, the code writing and maintenance will become difficult;
So Require.js solves both of these problems:
1. Implement the asynchronous loading of JS file to avoid the webpage losing its response;
2. Manage the dependencies between modules, facilitate the writing and maintenance of code;

Two require.js load
1. Load require.js
    <script scr= "js/require.js" defer async= "true" > </script> the
//Async property indicates that the file needs to be loaded asynchronously to prevent the Web page from being unresponsive; IE does not support this property, only supports defer, so defer is also written;
2. Load main.js
    <script src= "js/require.js" data-main= "Js/main" ></SCRIPT>
// The function of the Data-main property is to specify the main module of the Web program =>main.js, the file will be the first to be loaded require.js;
//Because require.js default file suffix name is js, so you can main.js abbreviated to main;

Main.js of the three main modules
1. If Main.js does not rely on any other module, it can be written directly to the JavaScript code;
Main.js
    alert (' Load succeeded! ');
2. If the main.js depends on the module, then the Require () function defined by the AMD specification is used;
//Main.js
    require ([' Modulea ', ' Moduleb ', ' Modulec '],function (Modulea,moduleb,modulec) {
       //...
   }) The
///require () function receives two parameters:
//Parameter one: An array that represents the dependent module, which is the three modules that the main module relies on;
Parameter two: The callback function, the module specified by the current polygon is loaded successfully, it will be called, and the loaded module will pass in the function as a parameter, so that the modules can be used inside the callback function;
///require () asynchronous load module, the browser does not lose response, it specifies the callback function, only the previous module is loaded successfully, will not run, solve the problem of dependency;
Instance:
    require ([' jquery ', ' underscore ', ' backbone '],function ($,_,backbone) {
        //...
   });

Four loading of modules
Using the Require.config () method, you can customize the load behavior of the module;
Require.config () is written on the head of the main module (main.js);
The parameter is an object, and the paths property of the object specifies the loading path of each module;
Set the following three modules of the file default and main.js in a directory;
Require.config ({
paths:{
"jquery": "Jquery.min",
"Underscore": "Underscore.min",
"Backbone": "Backbone.min"
}
});

If the loaded module and the main module are not in the same directory, the path must be specified individually;
Require.config ({
paths:{
"jquery": "Lib/jquery.min",
"Underscore": "Lib/underscore.min",
"Backbone": "Lib/backbone.min"
}
});
or change the base directory directly (BASEURL)
Require.config ({
BASEURL: "Js/lib",
paths:{
"jquery": "Jquery.min",
"Underscore": "Underscore.min",
"Backbone": "Backbone.min"
}
});

If the module is on a different host, you can also specify its URL directly
Require.config ({
paths:{
"jquery": "Https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"
}
});
Require.js requirements, each module is a separate JS file, so that if the loading of multiple modules, will be issued multiple HTTP requests, will affect the load speed of the page;
As a result, Require.js provides an optimization tool that, when the module is deployed, can be used to merge multiple modules into a single file, reducing the number of HTTP requests;

The five AMD module notation

Require.js loaded modules, using AMD specifications, that is to say, modules must be written in accordance with the requirements of AMD;
Specifically, the module must be defined by a specific define () function, and if a module does not depend on other modules, it can be defined directly in the Define () function;
Defining the Math module in Math.js
Math.js
Define (function () {
var add = function (x, y) {
return x+y;
};
return {
Add:add
};
});
Loading the math module in Main.js
Require ([' Math '],function (math) {
Alert (Math.add ());
});
If the module also relies on other modules, then the first parameter of the Define () function must be an array that indicates the dependency of the module;
Math.js
define ([' Mylib '],function (mylib) {
function foo () {
Mylib.dosomething ();
}
return {
Foo:foo
};
});
When the require () function loads the above module, the Mylib.js file is loaded first;

Six-load non-canonical modules

Load non-canonical modules, and use the Require.config () method to define some of their characteristics before loading with require ().
Require.config ({
shim:{
' Underscore ': {
Exports: ' _ '
},
' Backbone ': {
deps:[' underscore ', ' jquery '],
Exports: ' Backbone '
}
}
});
Require.config () receives a configuration object that, in addition to the paths attribute previously mentioned, has a shim attribute specifically designed to configure incompatible modules;
(1). Defines the Deps array, indicating the dependency of the module;
(2). Defines the exports value (the variable name of the output), indicating the name of the external invocation of the module;
For example: jquery plug-in
shim:{
' Jquery.scroll ': {
deps:[' jquery '),
Exports: ' JQuery.fn.scroll '
}
};

Seven Require.js plug-in

1.domready: You can have the callback function run after the page DOM structure is loaded;
Require ([' domready! '],function (DOC) {
Called Once the DOM is ready;
})
2.text and Image: Allows Require.js to load text and picture files;
define ([' Text!review.txt ', ' image!cat.jpg '],function (review,cat) {
Console.log (review);
Document.body.appendChild (CAT);
});

JavaScript Modular Programming (note)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.