Lor*_*ard 9 javascript circular-dependency dependency-management requirejs
为了修复循环依赖关系,读取requireJs文档建议exports用于为模块创建一个空对象,该对象可立即供其他模块参考.
我尝试这个代码,但它似乎不起作用.怎么了?
PS:
阅读用于查看输出的注释,
尤其是setTimeout调用中的B模块.
// A module
define([
'b'
], function (b) {
console.log('B:', b); // B, Object
var A = {
boo: 1
};
return A;
});
Run Code Online (Sandbox Code Playgroud)
// B module
define([
'a',
'exports'
], function (a, exports) {
console.log('A:', a); // A, undefined (as I was expecting)
exports.A = function () {
return a;
}
var B = {
bar: 1
};
setTimeout(function () {
console.log('exports.A', exports.A()); // exports.A undefined
// I would like to access the A object
// which is defined in A module
}, 500);
return B;
});
Run Code Online (Sandbox Code Playgroud)
// main.js
(function () {
define([
'a'
], function () {
});
}());
Run Code Online (Sandbox Code Playgroud)
我经常遇到使用 AMD 模块构建应用程序核心的循环问题,该核心既支持许多模块,又包含配置或其他有用的对象供这些模块使用。
我今天做了一些实验,看起来效果很好。
define(['exports', 'underscore', './config', './mediator'],
function (exports, _, Backbone, config, Mediator){
Core = /* ... */
// Publicize a core 'singleton' so that it's dependencies can access it, and so can modules that define it as a dependency themselves.
core = new Core()
exports.core = core //publicize it in a way that supports circularity
return core // And also publicize it normally
}
)
Run Code Online (Sandbox Code Playgroud)
这些对象都“===”彼此相等,所以这看起来非常有希望。
编辑:
上述方法在优化后不起作用。这是另一种可能的方法(未经测试): https://github.com/requirejs/example-multipage/blob/master/www/js/app/main1.js#L2
define(function (require) {
var $ = require('jquery'),
lib = require('./lib'),
Core;
Core = /* ... */
return new Core()
});
Run Code Online (Sandbox Code Playgroud)