8

I am in the following situation.

I am using requireJs to loads module and I don't want to use global variables.

The main.js is responsible to load the router.
Then the router loads the app and the app loads several subApps.

After everything has been initialised, the subApps needs the router for making router.navigate.

Here the schema:

main.js -> router -> app -> subApp -> router

Then I have a problem of Circular Dependencies and for that reason the router in subApp will be undefined.

What is the best way to reorganise my code or to fix this problem? Are there some example about this?

Lorraine Bernard
  • 13,000
  • 23
  • 82
  • 134
  • i thought requirejs was supposed to handle circular dependencies correctly... (i honestly don't know. i'm not a fan of requirejs) – Derick Bailey Jun 30 '12 at 16:21
  • Nope, it doesn't. It doesn't event tell you it's a circular dependency - things just stop working and some references become undefined. – Tony Abou-Assaleh Jun 30 '12 at 20:52

3 Answers3

5

the schema:

 main.js -> router -> app -> subApp -> router

is right.

If you are using backbone.marionette, in order to access the router from the app and subApp, without using global var, you should start the app in router in this way:


// router.js
YourApp.start(router: router);

// app.js
YourApp.addInitializer(function(options){
  // do useful stuff here
  var myView = new MyView({
    router: options.router
  });
  YourApp.mainRegion.show(myView);
});
antonjs
  • 14,060
  • 14
  • 65
  • 91
  • 1
    shouldn't the app just pass itself to the router? It seems odd that the router would start the app. What if you have multiple routers? @AntoJs – Evan Hammer Mar 10 '13 at 17:05
2

Subapp can raise events which router handles rather than having an explicit dependency on router

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
  • you say subApp can raise event, but to which module? If I try to import app from subApp I have the same Circular Dependencies problem. – Lorraine Bernard Jun 30 '12 at 08:47
2

In my project, I use the following dependency: main.js -> app -> router -> subApp.

In app.js, I create a single global variable that holds a pointer to my app:

define([...], function(...) {
return {
  initialize: function() {
    window.MyApp = new Backbone.Marionette.Application();
    // ...
    MyApp.start();
  }
};
});

This makes it extremely easy to access my app's regions from anywhere, as well as store global state information in one name space.

I tried doing it without the global app at first, but eventually gave up and found this approach to be a lot more flexible.

Tony Abou-Assaleh
  • 3,000
  • 2
  • 25
  • 37