Search code examples
javascriptbackbone.jsjavascriptmvcbackbone-routing

Optional route parameters in Backbone.js? (again)


I'm trying to set up routing in Backbone 0.9.10. I'd like to match routes of the following kind:

/england/
/england/birmingham
/france
/france/paris
... 

etc. This is what I have in my router at the moment:

var AppRouter = Backbone.Router.extend({
  routes: {
    "": "index",
    "(/:country)": "index",
    "(/:country)(/:city)": "index"
  },
  index: function(country, city) { 
      console.log('index', country, city);
  }
});
var StateApp = new AppRouter();
Backbone.history.start({ pushState: true });

I have two problems:

  1. The 'index' function isn't firing at all at the moment, whatever URL I go to = /, /england or anything else.
  2. I'm also not clear if the optional parameters will work the way I have set them up - is it OK to have two optional parameters in a row like this? I don't know how many countries I need to support yet, so I do want the country parameter to be a parameter, rather than specifying individual countries.

I'd much rather use proper URL routing than regex parsing if possible.


Solution

  • If you want, as in your example, to route all urls (including the root) to one method, your only need to define one route:

    routes: {
      "(:country)(/:city)": "index"
    }
    

    Because both parameters are optional, this will match:

    • "" (Empty string)
    • "england"
    • "england/london"

    If you want only the routes in format of england and england/london but not the root page /, declare a separate empty route, and make the :country part non-optional:

    routes: {
      "" : "home",
      ":country(/:city)": "index"
    }