Over a million developers have joined DZone.
Platinum Partner

Using Routers in Backbone.js

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

After taking a break for a few days and then joining my new employer, I'm writing this long pending post on Routers in Backbone. A Router can be considered as a Controller in a MVC application. Controller in any MVC application defines how the incoming request should be handled. For example, a Servlet in a J2EE application accepts the request and looks into the configuration and delegates the request to one of the handlers.

A Router for a client-side application works in a similar way. A Router is created by extending Backbone.Router. The only property that you need to define is the 'routes' property. The routes property is an object which maps the application's hashtags to a function. It defines various routes and the necessary action to take when that route is navigated. I say 'navigated' because a Backbone Router looks into the URL and sees the value after the hash (#) to delegate the incoming request to one of the defined handlers.

var AppRouter = Backbone.Router.extend({ 
	routes: {
		"": "index",
		"welcome": "welcome"
	index: function() {

	welcome: function() {
var appRouterInstance = new AppRouter();

As observed in the above code snippet, the first property is an empty string which maps to a login function. This is similar to how you would like to show an index page or a login page when the user first enters the URL in the address bar. The next property is a string "welcome" which maps to a function that shows a welcome page when the user logs in to the application. This function is invoked when '#welcome' is appended to the URL (a URL of form http://host/...#welcome). One can call navigate on the router instance specifying the route to navigate:

appRouterInstance.navigate('welcome', {trigger: true}) 
The second argument to the navigate method is an object where the 'trigger' key is set to true. This indicates that you want to update the URL as well as trigger the route function for the specified route. If trigger is set to false or if trigger is not specified then only the URL would be updated and the function defined for that route would not be invoked.

I've created a simple application that makes use of Routers and Views in Backbone.

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Sagar H Ganatra , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}