Using Routers in Backbone.js
Join the DZone community and get the full member experience.
Join For FreeA 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 Sagar Ganatra, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments