Platinum Partner
css,html5,javascript,tips and tricks,backbone.js

Using Routers in Backbone.js

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() {
		loginViewInstance.render();
	},

	welcome: function() {
		welcomeViewInstance.render();
	}
});
var appRouterInstance = new AppRouter();
Backbone.history.start();

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.

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}