Reputation: 5912
I'm rewriting a category tree view into a RequireJS and Backbone app.
The structure is simple: each category contains a collection of child categories.
However, the circular dependency problem becomes quickly apparent. The category model requires the category collection and the category collection requires the category model.
There is quick blurb about circular dependency in the RequireJS docs:
http://requirejs.org/docs/api.html#circular
However, it seems that I'm missing something because I'm still getting undefineds and/or errors. I think just seeing 'b' and not 'a' in the examples is keeping me from understanding.
Is anyone able to provide a simple example that might clarify? That, or a better way of structuring this that wouldn't require a circular dependency.
Upvotes: 4
Views: 1258
Reputation: 1724
Due to the circular reference, when require.js is loading "b" as a prerequisite for "a", it can't return a value for "a" because a's initModule()
has not been call yet. However, by the time b.somethingElse()
is called, module "a" has been initialized and the require("a")
call will return.
The following code shows what's inside both modules - the order in which they get loaded does not matter. I've changed it from the require.js example a little to make it more obvious.
// Inside a.js:
define(["require", "b"],
function initModule(require) {
return {
doSomehingWithA: function() { ...},
doSomethingElse: function(title) {
// by the time this function is called,
// require("b") will properly resolve
return require("b").doSomethingWithB();
}
}
}
);
// Inside b.js:
define(["require", "a"],
function initModule(require) {
return {
doSomethingWithB: function() {...},
doSomethingElse: function(title) {
// by the time this function is called,
// require("a") will properly resolve
return require("a").doSomethingWithA();
}
};
}
);
BTW, while in general circular references are a symptom of bad design, that's not always so. For example, I've implemented a widget factory module which, among other things, referenced a "container widget" module which then had to reference the factory in order to create its content. Perfectly legit.
Upvotes: 2