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:
/
, /england
or anything else. country
parameter to be a parameter, rather than specifying individual countries.I'd much rather use proper URL routing than regex parsing if possible.
You can make a URI parameter as optional by adding a question mark (“?”) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.
To add in an optional path parameter in React Router, you just need to add a ? to the end of the parameter to signify that it is optional. And then in your component you could access the GET parameters using the location.search prop that is passed in by React Router.
BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.
Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
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:
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With