the modular specification of JS:
Server side: Commonjs
Browser side: AMD ("Asynchronous module definition" abbreviation, meaning "asynchronous modules defined") second, why the use of AMD
The following code
var math = require (' math ');
Math.add (2, 3);
You must wait for the math.js load to complete, otherwise the load time will appear very long phenomenon
Third, define
define (ID, dependencies, factory);
Where: ID: module identification, can be omitted. Dependencies: Depends on the module that can be omitted. Factory: The implementation of a module, or a JavaScript object. The following is a simple three-tier architecture developed using AMD mode (base/UI layer/Application layer): Base.js
Define (function () {return
{
mix:function (source, target) {
}};
});
Ui.js
define ([' base '], function (base) {return
{
show:function () {
//TODO with module base
}
}
});
Page.js
define ([' Data ', ' UI '], function (data, UI) {
//init here
});
Data.js
Define ({
users: [], Members
: []
});
The above also demonstrates the three usages of define,
1, defining modules that are not dependent(base.js)
2, define the dependent module(ui.js,page.js)
3, define the data object module(data.js) Careful will find that there is another one does not appear, that is, named module
Define (' index ', [' data ', ' base '], function (data, base) {
//Todo
});
A named module is not recommended most of the time, generally by the packaging tools to merge multiple modules into a JS file to use. The order of the dependencies elements mentioned earlier and the factory one by one corresponds, in fact, not very rigorous. AMD began to get rid of the shackles of Commonjs, groundbreaking to put forward their own modular style. But then again made a compromise, compatible with the Commonjs modules/wrappings. That's how it can be written.
Define (function (Require, exports, module) {
var base = require (' base ');
Exports.show = function () {
//TODO with module base
}
};
Regardless of the extra layer of functions, the format and Node.js are the same: use require to get the dependency module and use exports to export the API.
four, require
Require ([module], callback);
The first parameter [module], which is an array whose members are the modules to be loaded, and the second parameter callback, is the callback function after the success of the load. If you rewrite the previous code into AMD, this is the following:
Require ([' math '], function (math) {
Math.add (2, 3);
});
Math.add () is not synchronized with the math module, and the browser does not feign death. So it's clear that AMD is better suited to the browser environment.
Currently, there are two JavaScript libraries that implement AMD specifications: Require.js and Curl.js