Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  77] [ 2]  / answers: 1 / hits: 23106  / 12 Years ago, thu, august 16, 2012, 12:00:00

I'm using Requirejs to load the JavaScript in our web app. The issues is that I'm getting an undefined object being passed to a module which, when used in other modules, is instantiated perfectly fine.



OK, here's the setup. My main.js file which requirejs runs on startup:



require.config({
baseUrl: /scripts,
paths: {
demographics: Demographics/demographics,
complaints: Complaints/complaints,
}
});

require([templates, demographics, complaints, crossDomain], function (templates, demographics, complaints) {
use strict;

console.log(0);
console.log(demographics === undefined);

demographics.View.display();
});


A lot of the config has been stripped to just the core files in this problem.



Here's Demographics.js:



define([ko, templates, complaints, globals, underscore], function (ko, templates, complaints, globals) {

// Stuff removed.
return {
View: view
};
});


and Complaints.js



define([
demographics,
ko,
templates,
complaints,
visualeffects,
globals,
webservice,
underscore,
typewatcher,
imagesloaded],
function (demographics, ko, templates, complaints, visualeffects, globals, webservice) {
use strict;


console.log(1);
console.log(demographics === undefined);
return {
View: view
};
});


The problem is this - in Complaints.js the demographics parameter passed via the define config is undefined. The console log out tells me that demographics === undefined is true.



However, when the main.js file executes, the demographics parameter passed to it is not undefined, it is, as expected, an instantiated object.



Now I'm stuck since I can't see why in complaints.js that demographics variable is undefined. Can anyone spot what I'm missing please?


More From » requirejs

 Answers
25

You have a circular dependency. The demographics module depends on complaints and complaints depends on demographics. As per the documentation:




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.




The solution, if you can't remove the circular dependency, is to asynchronously require one of the two modules within the other on demand (say when the view is instantiated instead of when the module that defines the view is executed). Again, the docs cover this topic fairly well.


[#83594] Wednesday, August 15, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darennevina

Total Points: 422
Total Questions: 128
Total Answers: 105

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;