AMD设计出一个简洁的写模块API:
define(id?, dependencies?, factory);
其中:
- id: 模块标识,可以省略。
- dependencies: 所依赖的模块,可以省略。
- factory: 模块的实现,或者一个JavaScript对象。
id遵循CommonJS Module Identifiers 。dependencies元素的顺序和factory参数一一
//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: []
});
以上同时演示了define的三种用法
- 定义无依赖的模块(base.js)
- 定义有依赖的模块(ui.js,page.js)
- 定义数据对象模块(data.js)
细心的会发现,还有一种没有出现,即具名模块
4,具名模块
define('index', ['data','base'], function(data, base) {
// todo
});
具名模块多数时候是不推荐的,一般由打包工具合并多个模块到一个js文件中时使用。
前面提到dependencies元素的顺序和factory一一对应,其实不太严谨。AMD开始为摆脱CommonJS的束缚,开创性的提出了自己的模块风格。但后来又做了妥协,兼容了 CommonJS Modules/Wrappings 。即又可以这样写
5,包装模块不考虑多了一层函数外,格式和Node.js是一样的:使用require获取依赖模块,使用exports导出API。
define(function(require, exports, module) {
var
base = require(
'base'
);
exports.show =
function
() {
// todo with module base
}
});
除了define外,AMD还保留一个关键字require。require 作为规范保留的全局标识符,可以实现为 module loader,也可以不实现。
目前,实现AMD的库有RequireJS 、curl 、Dojo 、bdLoad、JSLocalnet 、Nodules 等。
也有很多库支持AMD规范,即将自己作为一个模块存在,如MooTools 、jQuery 、qwery 、bonzo 甚至还有 firebug 。
0e1ae032fe70 6 月前
21c9fe46a025 6 月前