Multiple routers with backbone.js

Industrial picture Industrial · Jan 22, 2012 · Viewed 7.9k times · Source

Can I use multiple routers in backbone.js, that don't interfere with each other route-wise, without any issues? Or is there something that I should be concerned about?

Code sample:

myapp.routers.main = Backbone.Router.extend({
    routes : { "": "index" },
    index : function() { console.log("routed by main router");}    
});

myapp.routers.another = Backbone.Router.extend({
    routes : { "notmain": "index" },
    index : function() { console.log("routed by another router");}    
});

mainrouter = new vaikava.routers.main;
notmainrouter = new vaikava.routers.another;
Backbone.history.start();

Answer

taxilian picture taxilian · Jan 22, 2012

Yes, it works just fine; the only time you'd have a problem is if they have conflicting routes. There is a workaround that makes it work that way as well, but it's a bit of a hack.

As long as you avoid having multiple routers trying to handle the same route you should be fine.