Philippe Huibonhoa
Philippe Huibonhoa

Reputation: 423

Backbone > Multiple Routers and History.start

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.

Upvotes: 3

Views: 3237

Answers (2)

jcreamer898
jcreamer898

Reputation: 8189

You also may be able to check Backbone.History.started...

    var Router = Backbone.Router.extend({
        routes: {
            '': 'load'
        },
        initialize: function () {

        },
        load: function () {

        }
    });

    $(function () {
        new Router();
        if (!Backbone.History.started) {
            Backbone.history.start();
        }
    });

It was added recently in a pull request.

Be sure and check out Derick's Marionette plugin as well, it's pretty awesome.

Upvotes: 0

Derick Bailey
Derick Bailey

Reputation: 72868

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/

Upvotes: 8

Related Questions