Reputation: 2269
Im using requirejs to load several modules of a web app im building but am struggling to understand something. I have my main module requiring it dependancies but the other defined modules all reference each other in someway. so lets say the 'project/func' module may call a save function in the 'project/save' module. Now most of my code has resulted in undefined being errored.
From reading online maybe Ive hit something known as a circular reference?? Im not quite sure. I guess I need to know what Im doing wrong and how I should be doing it. Ive tried to put an example below with the main file calling the bootstrap method in one of the modules but that module calls another module at some point. This is just a small example. the real app has many many more modules and they all need to run functions inside each others if that makes sense.
//main require
require(['jquery', 'jqueryui', 'project/save', 'project/funcs', 'project/spec'], function($, ui, proSave, proFunc, proSpec){
proFunc.bootstrap();
});
//project/save
define(function(){
var save = function(){
//do some save stuff here
}
return {
save: save
}
});
//project/funcs
define(['project/save'], function(proSave){
var funcs = {
bootstrap: function(){
//do some stuff
funcs.func1();
},
func1: function(){
//do some stuff and save
proSave.save();
}
}
return {
funcs: funcs
}
});
Upvotes: 3
Views: 567
Reputation: 151380
RequireJS has documentation on circular dependencies that explains how to handle them:
If you define a circular dependency (a needs b and b needs a), then in this case when b's module function is called, it will get an undefined value for a. b can fetch a later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up a):
//Inside b.js: define(["require", "a"], function(require, a) { //"a" in this case will be null if a also asked for b, //a circular dependency. return function(title) { return require("a").doSomething(); } } );
So you have to write your code to be able to work with the fact that module definitions in circular dependencies will initially be undefined. The details of how you accomplish this are dependent on the specific structure of your application.
These words of wisdom, from the RequireJS documentation, are well worth paying attention to:
Circular dependencies are rare, and usually a sign that you might want to rethink the design.
[Emphasis added.] Very often, if module A depends on B and B depends on A, there's a subset of functionality to be extracted either from A or B and moved into a module C which would allow A to depend on C rather than B, and B to depend on C rather than A, and break the circular dependency. For the sake of everyone working with such code, this is the best route to take. Then, in the rare cases where the circularity cannot be removed, the documentation I cited above tells you how to approach it.
Upvotes: 5