Reputation: 2294
I want to make a sort of loader class. Consider:
config.js
define(function() {
return {
appViews : [
'baseViews',
'fullDocViews',
'docCreateViews',
'accountViews',
'fullDocViews',
'notifyViews'
]
}
}
loader.js
define(['config', 'underscore'], function (Config, _) {
var Loader = {};
_.each(Config.appViews, function (view) {
var include = 'views/'+view;
Loader[view] = require([include], function (Include) {
return Include;
});
});
return Loader;
});
fullDocViews.js
define(['loader'], function (Loader) {
var moduleView = Loader.baseViews.BaseView.extend({
// Loving life here...
})
});
This, however, creates a circular dependency, since calling the loader calls fullDocsView module. Is there any way that, in loader.js, I can exclude the calling module from the resulting hash of views?
So what I'm looking for is this:
define(['config', 'underscore'], function (Config, _) {
var Loader = {};
_.each(Config.appViews, function (view) {
if (view !== callingView) {
var include = 'views/'+view;
Loader[view] = require([include], function (Include) {
return Include;
});
}
});
return Loader;
});
Upvotes: 0
Views: 70
Reputation: 151401
There is a problem with your code but it is not the circular dependency. This won't work:
Loader[view] = require([include], function (Include) {
return Include;
});
Because:
The return value of a require
call which takes an array of dependencies is not a module. (It is a function named localRequire
, which is one of the incarnations of the require
function.)
The return value of the callback used for a require
call is swallowed by RequireJS.
Why is it this way, because a call to require like this is asynchronous. The module is going to be available at some indeterminate time in the future.
There is a require
call which returns a module value: require("module")
. You pass a single module name rather than an array. This kind of call either returns a module if it is already loaded, or fails right away.
As for the circular dependency, I do not believe RequireJS exposes the name of what module caused another module to be loaded. The way it handles circular dependencies is that if A requires B which requires A, then B must be ready to accept that when it is instantiated, the value it gets for A is going to be undefined
. It can then require A again later, and get a real value.
Upvotes: 2