Learn the simple yet powerful syntax for setting up routing in your Backbone.js single page application
Routes are one of the most important aspects of any single page application. Routes allow you to intercept browser address changes and act upon them accordingly. As per the moniker “single page application” suggests, after the completion of the initial page load, you never want the user to endure a round-trip to the server.
Backbone.js provides simple yet powerful abstraction for routing. In this series of articles, we will explore the core syntax and features that allow you to build-out routing for your single page application.
Extending Backbone.Router
Extending classes is an important topic to quickly review. In Backbone.js, when you want to create a router, you first need to extend the Router class. To be more specific, “Router()” is a JavaScript constructor function that is a property of the “Backbone” object. Extending the Router class allows you to leverage all of the existing functionality while adding more of your own. When you extend the Router class, you are creating a new constructor that inherits from the “Backbone.Router”. Once you have extended the Router class, you’ll then need to instantiate your new constructor.
Example # 1A
1 |
var AppRouter = Backbone.Router.extend(); |
Example # 1B
1 |
var AppRouter = Backbone.Router.extend( { } ); |
In example # 1A, we create a new variable named: “AppRouter”, and set it to the return value of Backbone.Router’s “extend” method. The “extend” method allows you to create a class that inherits from another and is available in a number of Backbone objects. In this case, our class does not do too much, so we have a bit more work to do.
In example # 1B, notice that an object is being passed to the extend method. This object is empty, and our AppRouter class still does not offer much value. The main points to remember as we move forward are:
You create a router by extending the Backbone.Router class, using the “extend” method
The extend method requires an object as its sole argument
The result of extending the Backbone.Router class is a new class (or constructor), which will need to be instantiated
NOTE: Our variable begins with a capital “A” (i.e. “AppRouter”). This is not required but it is recommended because in JavaScript (as well as other languages), classes usually have an initial capital letter in their name.
Example # 2
1 2 3 4 5 6 7 8 9 10 11 12 |
var AppRouter = Backbone.Router.extend({ routes: { "": "defaultRoute", "info": "info" }, defaultRoute: function () { $('#main').html('<div class="mainMessage">This is the default route</div>'); }, info: function () { $('#main').html('<div class="mainMessage">This is the "Info" page</div>'); } }); |
In Example # 2, we have added quite a bit of functionality to the object that is passed into the extend method. This object has three properties: “routes”, “home”, and “info”.
The “routes” property is critical. This property is an object. The properties of the object are the routes that we want to map. In this case, there are two:
- “” – When no route is requested, map to “defaultRoute”
- “into” – When an “info” route is requested, map to “info”
But, what are “home” and “info”? Well, they are the other two two properties of the object passed to the extend method, and they are method (i.e. they are properties whose value is a function). So, when no route is requested, Backbone will execute the “defaultRoute” method, and when the “info” route is requested, the “info” method will be executed.
This example is very basic; you are not likely to create a single page application with only two routes. What is important to remember is that as you build out your application, this is a pattern you will follow:
- You extend the Backbone.Router class by passing an object to the extend method
- In the object you pass to the extend method, you provide a “routes” property
- The “routes” property is an object that has a set of properties that map to methods
- The methods you map to are functions that handle the route request
There are still a couple of steps left in order to get our new Router to a working state.
Example # 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var AppRouter = Backbone.Router.extend({ routes: { "": "defaultRoute", "info": "info" }, defaultRoute: function () { $('#main').html('<div class="mainMessage">This is the default route</div>'); }, info: function () { $('#main').html('<div class="mainMessage">This is the "Info" page</div>'); } }); var app = new AppRouter(); $(document).ready(function() { Backbone.history.start(); }); |
In Example # 3, we take two further steps that are needed in order to get our Backbone.js router to a working state:
- We instantiate our AppRouter class
- We call Backbone.history.start(); from the jQuery document.ready method.
The first step is required because even though we extended the Backbone.Route class, we need to instantiate the new class (or constructor) that we created. A detailed discussion of the Backbone.history object and its “start” method is beyond the scope of this article, but suffice to say that this step is needed in order to get the routing process started. Wrapping it in a call to jQuery’s document.ready method is generally a good idea so that you can be sure that the routing does not start until the DOM is ready.
HERE IS THE LINK TO THIS ARTICLE’S WORKING EXAMPLE:
http://examples.kevinchisholm.com/backbone/routes/basics/html/part-i.html
How to Demo:
Click the “Home” and “Info” links in the page’s navigation menu. As you do this, look closely at the browser’s address bar. You’ll see that “#/” and “#/info” are appended to the address. These are routes. The code that we worked on in this article intercepts these route requests and prevents the page from making a request to the server located at: “http://examples.kevinchisholm.com/”. Accordingly, messages that are results of the functions we execute upon each route request are rendered in the DOM.
Details
When the page loads, you will see the following message: “This is the default route”.The reason for this is that when we extended Backbone.Route, we specified that if no route was requested, the “defaultRoute” method should execute. If you click the “Info” menu item, you’ll see the message: This is the “Info” page. This is because we specified that when the “info” route is requested, the “info” method should execute.
Summary
In this article, we were introduced to Backbone’s routing feature. We learned about extending classes, and specifically, the syntax needed to create a constructor function that inherits from Backbone.Router. We discussed the steps needed to configure our router so that a number of possible routes can be anticipated and acted upon accordingly.
Helpful Links for Routing in Backbone.js
http://backbonetutorials.com/what-is-a-router/
http://www.codebeerstartups.com/2013/01/routers-in-backbone-js-learning-backbone-js
[…] the first part of this series: Getting Started with Backbone.js Routes – Part I: Introduction, we learned how to set up routing in a single page web application. We covered two kinds of routes: […]