Reading the requireJs documentation,
in order to fix the Circular Dependencies, is suggested to use exports
to create an empty object for the module that is available immediately for reference by other modules.
I try this code but it seems to do not work. What is wrong?
P.S.:
read the comments for seeing the output,
especially the B module inside setTimeout call.
// A module
define([
'b'
], function (b) {
console.log('B:', b); // B, Object
var A = {
boo: 1
};
return A;
});
// 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;
});
// main.js
(function () {
define([
'a'
], function () {
});
}());
In software engineering, a circular dependency is a relation between two or more modules which either directly or indirectly depend on each other to function properly. Such modules are also known as mutually recursive.
There are a couple of options to get rid of circular dependencies. For a longer chain, A -> B -> C -> D -> A , if one of the references is removed (for instance, the D -> A reference), the cyclic reference pattern is broken, as well. For simpler patterns, such as A -> B -> A , refactoring may be necessary.
To reduce or eliminate circular dependencies, architects must implement loose component coupling and isolate failures. One approach is to use abstraction to break the dependency chain. To do this, you introduce an abstracted service interface that delivers underlying functionality without direct component coupling.
Maven does not allow cyclic dependencies between projects, because otherwise, it is not clear which project to build first. So you need to get rid of this cycle.
You should be able to use the synchronous version of require()
in your B module to access the "A" module:
// B module
define([
'a',
'exports'
], function (a, exports) {
console.log('A:', a); // A, undefined (as I was expecting)
exports.A = function () {
return require('a');
}
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With