Backbone Network> Multiple Routers and History.start

I would like to have several routers living on the same page for modularity. I initialize routers on $(document).ready()in different js files. When I had only one router that worked fine, because I could call History.start()right after the router was initialized, but now that I have several routers that can be initialized from different files, I'm not sure when to call History.start().

For instance:

<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()
});

as well as for the router 2.

Is the best solution to add a new $(document).ready()one that calls History.start()at the end of the page? I do not think that ready-made doc calls are blocked, so this does not mean that the race condition in which all routers were not initialized by the time History.start().

+3
source share
2 answers

You only need to call Backbone.history.start()your application once, and the only criterion when you call it is that at least one router should already be created.

So you can easily do this:


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


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


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

I do similar work with routers on a regular basis, and I often launch new routers after the page loads, and the user interacts with the page.

FWIW, , , Backbone.Marionette : http://lostechies.com/derickbailey/2011/12/16/composite-javascript-applications-with-backbone-and-backbone-marionette/

+8

Backbone.History.started...

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

        },
        load: function () {

        }
    });

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

.

Derick Marionette, .

0

All Articles