0

I am trying to modify my code such that it works with Require.js but i am running into an issue where some dependencies are undefined where i believe they should be.

A minimal working example is given by the below files:

main.js:

// Configure require.js
requirejs.config({
  baseUrl: "js/app",
});

require(["app"], function(app) {
  app.init();
});

app.js:

define( ["container", "renderer"], function ( CONTAINER, RENDERER) {
  return {
    init: function () {
      CONTAINER.init();
      RENDERER.init();
      console.log(CONTAINER, RENDERER)
    },
  }
});

container.js:

define( ["renderer"], function ( RENDERER ) {
  // define container
  var container = new Object();
  return {
    container: container,
    init: function() {
      console.log(RENDERER)
    },
  }
});

renderer.js:

define( ["container"], function ( CONTAINER ) {
  var renderer = new Object();
  return {
    renderer: renderer,
    init: function() {
      console.log(CONTAINER);
    },
  }
});

The problem is that in renderer.js CONTAINER is undefined. The console shows this when run in a browser:

enter image description here

Why is CONTAINER undefined in renderer.js while it is defined just fine in app.js?

nluigi
  • 1,263
  • 2
  • 15
  • 35
  • avoid circular dependencies :) http://stackoverflow.com/questions/4881059/how-to-handle-circular-dependencies-with-requirejs-amd – jan Nov 14 '15 at 00:22

1 Answers1

2

Circular reference between container and renderer.

I recall that require.js specifically does not allow such circular references, where container requires renderer and renderer requires container.

If you want the circular reference between the objects you can get around require's restriction by having app set a property in renderer, or in container, for example, by calling a function like ...

CONTAINER.init(RENDERER)

...from within App...

Obligatory verbose warning about the evils of circular reference omitted for brevity.

joshp
  • 1,886
  • 2
  • 20
  • 28