Richard
Richard

Reputation: 32899

Variables in Backbone.js routes: regex required?

I'd like a Backbone routing setup that works as follows:

Currently I have (as a crude first attempt):

  var AppRouter = Backbone.Router.extend({
      routes: {
          "ca/:str": "handleByCountry",
          "us/:str": "handleByCountry",
          "*route": "home" 
      },
      handleByCountry: function(str){
          console.log('ROUTE handleByCountry', route); 
          // how to get the country? parse route by hand?
      },
      home: function(route){
          this.navigate('/');
      },
  });

This has the following problems:

Also, is forwarding other routes to /, as I am doing, good practice?

Upvotes: 1

Views: 1740

Answers (1)

Tom Tu
Tom Tu

Reputation: 9583

Yes you can write single route for ca and us

routes: {
    ":country/:str": "handleByCountry",
    "*route": "home" 
},

handleByCountry: function(country, str){

    console.log('country is:', country, ' and str is: ', str, route); 
},

We've used similar pattern to redirect all unkown routes to 404 in a same manner as you did with redirecting to home so I believe it's a correct way to do it

If you need more custom routes you can pass custom regular expression as a route instead of backbone route string using the route method in the router initializer.

Upvotes: 3

Related Questions