Routing is a method of triggering state. In your site you have paths that bring a user to different pages that provide specific content. Routes are just like that but for a single page. They provide a way to trigger a specific state on that page. A good example is search.
Assume that a page may shows a list of items the user has ordered. For that the path could look like “www.mySite.com/user/orders/2012/”. We assume there is a view in that page that will show the details the orders that match a search term a modal. The page could have script that searches though the data, using Underscore.js possibly, to produce the select orders and then launch a modal to show them. A route can be the trigger to perform the search and show the modal. Afterward the route in the app can then be used by the user to book mark the result with out the general mess of a search/query string in the URI. The resulting URI would look something like this “www.mySite.com/user/orders/2012/#search/orange” for the users search for orders with the keyword “orange” in them. As a application gets more complicated in its views and states routes become a good way to trigger and return to specific sates in your application.
So how do you get started with Routes?
First start to extend the route class:
var PageRouter = Backbone.Router.extend({});
The route extend function takes a hash as its parameter. The hash has key with all the routes and keys for the functions the routes will call when they are matched:
'routes': { //Key for routes followed by the route map
'pathOne/someThing/:aValue': 'RouteOne', //path and trigger name
'pathTwo/*everything': 'RouteTwo'
},
//Each trigger name and action for the path mapping
'RouteOne': function (aValue) {
//Do Something
}
The last part is to create an instance of your router and then to start the backbone history module.
var pRte = new PageRouter(); Backbone.history.start();
Navigating to a route will trigger the function its bound to to run. The function will be passed all the keys defined in the path as and parameters. Key can be either specific parts of the path or splats of what ever is left. Keys are defined like “reports/:year/:month/:day/” where the function that is called when that path is matched could have the parameters (year, month, day).
The last thing to note is that routes are matched from first to last. So if you define “search/ducks”, above “search/*term” the latter will never respond to a path of “#search/ducks” because the first route will catch it. That being said making the last route “*anything” is a good way to catch all the routes that don’t match anything else.
