Jason Evans Jason Evans - 5 months ago 19
Javascript Question

Undefined object being passed via Requirejs

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?

Answer

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.