The Backbone.Router object is used for navigation inside your application. You should use it if you want to access different view pages by hitting the appropriate URLs. Users can also navigate through an application using the browser's history bar.
By default, the router works well with hash paths, such as index.html#path/to/page. Any string that is placed after a hash character is supposed to be a route and is processed by Backbone.Router.
Here, we are going to explain how to create our own router in our application:
Define a router by extending Backbone.Router into the Workspace object and setting pairs of routes and callback functions for them inside the routes property that is passed to the extend() method. This gives the router information of which callback should be executed in case the appropriate route is accessed.
var Workspace = Backbone.Router.extend({ routes: { // Default path. '': 'invoiceList', // Usage of static path. 'invoice': 'invoiceList', }, });
Add a callback method to the router object.
invoiceList: function() { var invoiceListView = new InvoiceListView({ el: 'body' }); invoiceListView.render(); }
If the user visits index.html or index.html#invoice, the invoiceList() callback is executed, which renders InvoiceListView. Here, InvoiceListView is a simple stub.
Tell Backbone to use this router and start the application.
$(document).ready(function () { new Workspace(); Backbone.history.start(); });
Here, we create a new Workspace object and execute the start() method of the Backbone.history object that is used for global application routing. As always, we should start our application right after the HTML page has loaded completely.
Backbone.Router is used just for defining routes and callbacks. All the important jobs are done by Backbone.history that serves as a global router (per frame) to handle hashchange or pushState events, match the appropriate route, and trigger callbacks. You shouldn't ever have to create an instance of the global router—you should use the reference to Backbone.history that will be created for you automatically if you make use of routers with routes.
Backbone router allows the defining of routes with parameters, which we are going to explain in this section.
If we want the router to parse parameters in a URL, we need to use the colon character (:) before the parameter's name. Here is an example that demonstrates how Backbone.Router parses URLs with a parameter.
var Workspace = Backbone.Router.extend({ routes: { // Usage of fragment parameter. 'invoice/:id': 'invoicePage', }, // Shows invoice page. invoicePage: function(id) { var invoicePageView = new InvoicePageView({ el: 'body', // Pass parameter to the view. id: id }); invoicePageView.render(); }, });
Paths such as index.html#invoice/1 and index.html#invoice/2 will be parsed by a router. In both cases, the invoicePage() callback is executed; it passes the ID parameter to InvoiceLPageView and renders it.