How to initialize multiple routers?

100 views Asked by At

I have two resources in Routers: Students and Colleges.

class App.Routers.Colleges extends Backbone.Router
  routes:
   "index": 'index'
class App.Routers.Students extends Backbone.Router
  routes:
   'index': 'index'
   'new': 'newStudent'

How to initialise these two routes such that they work?

I have tried to initialize like the code below but it's not working.

window.App =
 Models: {}
 Collections: {}
 Views: {}
 Routers: {}
 initialize: ->
   new App.Routers.Students
   new App.Routers.Colleges
   Backbone.history.start()
 $(document).ready ->
   App.initialize()

When I try to run the above code, it's only showing me the data in new App.Routers.Colleges in both colleges and students div.

1

There are 1 answers

0
Emile Bergeron On

Routes in routers are added to the global Backbone.history object. So any identical route overrides the precedent ones. Even non-identical routes may override a similar but more specific route if defined after.

When instantiating a new Router, its constructor calls _bindRoutes which parses routes from the last to the first so specific routes should be defined first and the more generic routes after, ending with any catch-all route.

Every URL needs to be unique, so you could namespace every router with a prefix:

class App.Routers.Colleges extends Backbone.Router
  routes:
   'colleges': 'index'
class App.Routers.Students extends Backbone.Router
  routes:
   'students/new': 'newStudent'
   'students': 'index'

Or you could use (or make your own) sub-router/controller.