BackBone Tutorial - Part 7: Understanding Backbone.js Routes and History
Join the DZone community and get the full member experience.
Join For Freein this article, we will try to look at routes in backbone.js. we will try to understand how routes can be useful in a large scale single page applications and how we can use routes to perform action based on requested url.
background
we have been using web application for more than 2 decades now. this has made us tuned to some of the functionalities that the websites provide. one such functionality is to be able to copy the url and use it for the viewing the exact application area that we were viewing before. another example is the use of browser navigation buttons to navigate back and forth the pages.
when we create single page applications, there is only one page being rendered on the screen. there is no separate url for each page. the browser is not loading the separate pages for separate screens. so how can we still perform the above mentioned operations even with a single page application. the answer is backbone routes.
link to complete series:
- backbone tutorial – part 1: introduction to backbone.js [ ^ ]
- backbone tutorial – part 2: understanding the basics of backbone models [ ^ ]
- backbone tutorial – part 3: more about backbone models [ ^ ]
- backbone tutorial – part 4: crud operations on backbonejs models using http rest service [ ^ ]
- backbone tutorial – part 5: understanding backbone.js collections [ ^ ]
- backbone tutorial – part 6: understanding backbone.js views [ ^ ]
- backbone tutorial – part 7: understanding backbone.js routes and history [ ^ ]
using the code
backbone routes and history provides us the mechanism by which we can copy the urls and use them to reach the exact view. it also enables us to use browser navigation with single page applications. actually routes facilitate the possibility of having deep copied urls and history provides the possibility of using the browser navigation.
life without router
let us try to create a simple application that is not using the router. lets create three simple views and these views will be rendered in the same area on our application based on user selection. let create 3 very simple views.
var view1 = backbone.view.extend({ initialize: function() { this.render(); }, render: function() { this.$el.html(this.model.get('message') + " from the view 1"); return this; } }); var view2 = backbone.view.extend({ initialize: function() { this.render(); }, render: function() { this.$el.html(this.model.get('message') + " from the view 2"); return this; } }); var view3 = backbone.view.extend({ initialize: function() { this.render(); }, render: function() { this.$el.html(this.model.get('message') + " from the view 3"); return this; } });
now we need a view that will contain the view and render it whenever the user makes a choice on the screen.
var containerview = backbone.view.extend({ mychildview: null, render: function() { this.$el.html("greeting area"); this.$el.append(this.mychildview.$el); return this; } }); var containerview = backbone.view.extend({ mychildview: null, render: function() { this.$el.html("greeting area"); this.$el.append(this.mychildview.$el); return this; } });
now we need a view that will contain the view and render it whenever the user makes a choice on the screen.
now lets create a simple div on the ui which will be used as elto this containerview. we will then position three buttons on the ui which will let the user to change the view. below code shows the application setup that is creating the container view and the functions that will get invoked when the user selects the view from screen.
var greeting = new greetmodel({ message: "hello world" }); var container = new containerview({ el: $("#appcontainer"), model: greeting }); var view1 = null; var view2 = null; var view3 = null; function showview1() { if (view1 == null) { view1 = new view1({ model: greeting }); } container.mychildview = view1; container.render(); } function showview2() { if (view2 == null) { view2 = new view2({ model: greeting }); } container.mychildview = view2; container.render(); } function showview3() { if (view3 == null) { view3 = new view3({ model: greeting }); } container.mychildview = view3; container.render(); }
now lets run the application and see the results.
when we click on the buttons we can see that the actual view is getting changes but the url is not getting changes. that would mean that there is no way, i can copy a url and directly go to any view. also, the second thing to note here is that if we press the browser back button, the application will go away(since its still on the same single page from the browser’s perspective).
note: please download and run the sample code to see this in action.
hello backbone routes
now the above problem can very easily be solved using backbone routesand history. so lets try to first look at what are backbone routes.
backbone routes are simple objects that are handle the incoming route value from the url and the invoke any function. lets create a very simple route class for our application.
var myrouter = backbone.router.extend({ });
in our route class we will have to define the routes that our application will support and how we want to handle them. so first lets create a simple route where only the url is present. this usually is the starting page of our application. for our application lets just open view1 whenever nothing is present in the route. then if the request is for any specific view we will simply invoke the function which will take care of rendering the appropriate view.
var myrouter = backbone.router.extend({ greeting: null, container: null, view1: null, view2: null, view3: null, initialize: function() { this.greeting = new greetmodel({ message: "hello world" }); this.container = new containerview({ el: $("#rappcontainer"), model: this.greeting }); }, routes: { "": "handleroute1", "view1": "handleroute1", "view2": "handleroute2", "view3": "handleroute3" }, handleroute1: function () { if (this.view1 == null) { this.view1 = new view1({ model: this.greeting }); } this.container.mychildview = this.view1; this.container.render(); }, handleroute2: function () { if (this.view2 == null) { this.view2 = new view2({ model: this.greeting }); } this.container.mychildview = this.view2; this.container.render(); }, handleroute3: function () { if (this.view3 == null) { this.view3 = new view3({ model: this.greeting }); } this.container.mychildview = this.view3; this.container.render(); } });
now this route class contains the complete logic of handling the url requests and rendering the view accordingly. not only this, we can see that the code which was written in a global scope earlier i.e. the controller and view creation all that is put inside the route now. this would also mean that routes not only provide us deep copyable urls but also could provide more options to have better structured code(since we can have multiple route classes and each route class can handle all the respective views for the defined routes).
backbone history and instantiating routes
backbone history is a global router that will keep track of the history and let us enable the routing in the application. to instantiate a route and start tracking the navigation history, we need to simply create the router class and call backbone.history.start for let the backbone start listening to routes and manage history.
$(document).ready(function () { router = new myrouter(); backbone.history.start(); })
invoking and requesting routes
a route can either be invoked from the other parts of the application or it can simply be requested by the user.
- invoking route: application wants to navigate to a specific route (this can be done by navigating to a route by calling the navigate function: router.navigate('view1');
- route request: user enters the fully qualified url (this will work seamlessly)
let us run the application and see the result.
passing parameters in the routes
we can also pass parameters in the route. lets us try to create a new route where the user will request for a view in a parameterized manner. parameters can be defined as “ route/:param”
var myrouter = backbone.router.extend({ greeting: null, container: null, view1: null, view2: null, view3: null, initialize: function () { this.greeting = new greetmodel({ message: "hello world" }); this.container = new containerview({ el: $("#rappcontainer"), model: this.greeting }); }, routes: { "": "handleroute1", "view/:viewid": "handlerouteall" }, handlerouteall: function (viewid) { if (viewid == 1) { this.handleroute1(); } else if (viewid == 2) { this.handleroute2(); } else if (viewid == 3) { this.handleroute3(); } }, handleroute1: function () { if (this.view1 == null) { this.view1 = new view1({ model: this.greeting }); } this.container.mychildview = this.view1; this.container.render(); }, handleroute2: function () { if (this.view2 == null) { this.view2 = new view2({ model: this.greeting }); } this.container.mychildview = this.view2; this.container.render(); }, handleroute3: function () { if (this.view3 == null) { this.view3 = new view3({ model: this.greeting }); } this.container.mychildview = this.view3; this.container.render(); } });
the above route can be invoked by passing view/2 as url. the viewid passed to the router will be 2.
having optional parameters in routes
we can also pass optional parameters in the routes, lets try to pass a simple parameter in the above defined route and see how it works. optional parameters can be defined as “ route(/:param)“.
var myrouter = backbone.router.extend({ routes: { "": "handleroute1", "view1": "handleroute1", "view2": "handleroute2", "view3": "handleroute3", "view/:viewid(/:msg)": "handlerouteall" }, handlerouteall: function (viewid, msg) { if (msg) { alert(msg); } } });
in the above code, if we pass the second parameter i.e. view/2/test, the alert will be shown else not.
note: the route definition can also contain complex regex based patterns if we need one route to handle multiple urls based on some regular expression.
point of interest
in this article we saw backbone.js routes. we saw how routes enable us to create bookmarkable urls and will let the user request a view based on url. we also looked at how we can use browser navigation by using backbone history. this has been written from a beginner’s perspective. i hope this has been informative.
download sample code for this article: backboneroutessample
Published at DZone with permission of Rahul Rajat Singh, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments