Search code examples
javascriptbackbone.jsurl-routingmarionette

Multiple Backbone.Routers and the default route -- order of matching routes/loading routers


Application that i'm coding is getting bigger and bigger and so far i've been using just one router for everything. I wanted to split it into two separate routers (for starters, more coming of course) like this:

class window.UFO.Routers.App extends Backbone.Router
  routes:
    #root
    ''                         : 'root'
    #not found
    '*notFound'                : 'notFound'

class window.UFO.Routers.Companies extends Backbone.Router
  routes:
    'companies/new/:angellist' : 'companiesNew'
    'companies/new'            : 'companiesNew'
    'companies/:id/edit'       : 'companiesEdit'
    'companies/:id/edit/people': 'companiesPeople'
    'companies/:id/edit/people/:preselect': 'companiesPeople'

There is an issue though: notFound route is triggered every time i try to access one of companies routes. I'm guessing it's because App router is loaded and initailized first (i'm using rails asset pipeline).

Do you know any workaround for this problem? Maybe a way to force Backbone to check all available routers before matching to *notFound route?

btw. we are using Backbone.Marionette, so solutions may use tools and code from it.


Solution

  • Vlad Niktin's comment has lead me in correct direction. However, actual url matching order is reverse of router initialization order. So, to make sure that '*notFound' route is matched last you have to load App router very first.

    My code, using Marionette initializers:

    window.APP.addInitializer ->
    
      appRouter = new window.APP.Routers.App
    
      companiesRouter = new window.APP.Routers.Companies
      sessionsRouter = new window.APP.Routers.Sessions
      roundsRouter = new window.APP.Routers.Rounds
    

    I'm still not sure if that's the optimal solution as you always have to remember to add another line to this initializer for each new router.