Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone > Multiple Routers and History.start

Tags:

backbone.js

I'd like to have multiple routers living on a single page for modularity. I initialize the routers on $(document).ready() in different js files. When I had just one router that worked fine because I could call History.start() right after initializing the router, but now that I have multiple routers that could be initialized from different files, I'm not sure when to call History.start().

For example:

<script src="router1.js" type="text/javascript"></script>
<script src="router2.js" type="text/javascript"></script>

In router1.js:

$(document).ready(function(){
  new Core.Routers.Router1()
});

and likewise for router2.

Is the best solution just to add a new $(document).ready() that calls History.start() at the end of the page? I don't think the doc ready calls are blocking, so doesn't that introduce a race condition where all the Routers may not have been initialized by the time History.start() has been called.

like image 325
Philippe Huibonhoa Avatar asked Jan 27 '26 07:01

Philippe Huibonhoa


1 Answers

You only need to call Backbone.history.start() once in your app and the only criteria for when you call it is that at least one router has to be instantiated already.

So, you could easily do this:


$(function(){
  new MyRouter();
  Backbone.history.start();
});


$(function(){
  new AnotherRouter();
});


$(function(){
  new AndMoreRouters();
});

I do a similar thing with routers on a regular basis, and I often start up new routers long after the page has been loaded and the user is interacting with the page.

FWIW though, you might be interested in the idea of initializers that I have in my Backbone.Marionette plugin and documented as part of this blog post: http://lostechies.com/derickbailey/2011/12/16/composite-javascript-applications-with-backbone-and-backbone-marionette/

like image 81
Derick Bailey Avatar answered Jan 29 '26 00:01

Derick Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!