Routers in Backbone.JS: Part 7

Before reading this article, I would like to recommend you go through my previous articles on this series of Backbone.js.

Routers in Backbone

Backbone.Router enables an application with URL routing and history capabilities. It enriches something with the methods for routing of the web applications with permalinks (linkable, bookmarkable and shareable URLs) of locations in the app and connects them to the actions and events.
                              

To make bookmarkable code, it is necessary to call Backbone.history.start() or Backbone.history.start({pushState: true}) after the application has finished creating all of the routers.

extend

Backbone.Router.extend(properties, [classProperties])

A Router can be defined by extending the Backbone.Router class, this is similiar to what we did with other modules of Backbone in the previous articles of this series. When we are extending Backbone.Router we are actually creating a new constructor that inherits from the Backbone.Router.

  1. var routers = Backbone.Router.extend({ // Creating a Backbone Router  
  2.     //routes and functions here  
  3. });  
example
  1. var routers = Backbone.Router.extend({  
  2.     routes: {  
  3.         """Route1",  
  4.         "Route2""Route2"  
  5.     },  
  6.     Route1: function () {  
  7.         //-----------  
  8.     },  
  9.     Route2: function () {  
  10.         //------------  
  11.     }  
  12. });  
In the preceding example, we added properties into the extend method, namely Route1 and Route2. These properties are actually the routes that we want to map. In this case, when Route1 is requested, it will map to the Route1, when Route2 is requested Route2 will map. 

When building an application all we need to know is the pattern to follow. First we extend the Backbone.Router class, then we an object to the extend method. We will provide properties like routes in the object, by which it maps to methods.

constructor / initialize

new Router([options])

The constructor will be called during Router instantiation.

  1. var route = new routers()// instantiation  
navigate

router.navigate(fragment, [options]) 

If we want to save our application as a URL, we call navigate to update.

  1. openPage: function(pageNumber) {  
  2.     this.document.pages.at(pageNumber).open();  
  3.     this.navigate("page/" + pageNumber);  
  4. }  
We can also call the route function by setting the trigger option to true. 

  1. app.navigate("help/troubleshooting", { trigger: true });  
If we wish to update the URL without creating an entry into the browser's history, we do it by setting the replace option to true.
  1. app.navigate("help/troubleshooting", { trigger: true, replace: true });  
execute

router.execute(callback, args)

router.execute(callback, args)
is called internally within the router, its corresponding callback is executed whenever a route is matched. We can also do custom parsing of our routes by overriding the method. For example:
  1. var Router = Backbone.Router.extend({  
  2.     execute: function (callback, args) {  
  3.         args.push(parseQueryString(args.pop()));  
  4.         if (callback) callback.apply(this, args);  
  5.     }  
  6. });  
Router Paramater

A Router parameter provides information to certain routes. We use a router parameter, we append a slash followed by colons and a parameter's name. A parameter's name will be available to the function pointed to by the router. 

  1. route: view/:id  
Optional Parameter

Backbone.Router also allow us to ask for an optional parameter in the route, this can be done by simply surrounding it in parenthesis (/:optional parameter). 
  1. routes: {  
  2.     'category/:name(/:page)' : 'showCategory'   
  3. }  
Dynamic Routing

If we want to retrieve a post with a variable id and also we we want the URL string to should be quite friendly, many of the frameworks allow us to do so. Suppose we have a URL string like abc.xyz/#/view/9 and we want to retrieve the id in the string. This can be done as in the following:
  1. var AppRouter = Backbone.Router.extend({  
  2.     routes: {  
  3.         "view/:id""getview",  
  4.         "*actions""defaultRoute"  
  5.     }  
  6. });  
  7. // Instantiate the router  
  8. var viewrouter = new AppRouter;  
  9. viewrouter.on('route:getview'function (id) {  
  10.     alert("Get view number " + id);  
  11. });  
  12. app_router.on('route:defaultRoute'function (actions) {  
  13.     alert(actions);  
  14. });  
  15. Backbone.history.start();  
Backbone uses :params and *splats.

":params" match any URL components between slashes whereas "*splats" match any number of components, that is always a last variable in our URL.
  1. routes: {  
  2.     'folder/*path''download'//splats  
  3.     '*default''default'  
  4. }  

 Summary

We got an overview of Backbone.Router with various methods and parameters.

That's it folks!

Up Next
    Ebook Download
    View all
    Learn
    View all