Reputation: 32899
I'd like a Backbone routing setup that works as follows:
/country/[any string]
, where country
is either us
or ca
, should both go to handleByCountry(country, location)
/
and be handled by handleHome
.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:
ca
and us
? I need some kind of conditional variable, maybe a regex.handleByCountry
? Do I need to parse the route string again?Also, is forwarding other routes to /
, as I am doing, good practice?
Upvotes: 1
Views: 1740
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