This tutorial is about BackboneJS Routes.

BackboneJS Tutorial series:

  1. Backbone.js for Absolute Beginners - Getting started (Part 1: Intro)
  2. Backbone.js for absolute beginners - getting started (part 2: Models, Collections and Views)
  3. Backbone.js for absolute beginners - getting started (part 3: CRUD)
  4. Backbone.js for absolute beginners - getting started (part 4: Routers) 👈 you are here

Backbone.Router

You could build web application without using the routers. However, if you want to make reference to certain ‘state’ or location of the web application, you need a reference (link/URL) to it. This is where routers come to rescue.

Routing in most of JS application are achieved by hash-tags. E.g. If you take a look of Gmail URL you will see something like:

https://mail.google.com/mail/u/0/#inbox/139c0d48e11d986b

where the #inbox/139c0d48e11d986b is the hash-tag which reference some email location.

In backbone, routes are hash maps that match URL patterns to functions. You can use parameter parts, such as todos/:id, or using splats file/*path you will match all the parameters from the splat on. For that reason, the splat parameter should be always the last matcher.

Initializing the Router

In our Todo app, we are going to use routers to filter between the tasks that are pending and the ones that have been completed. So, let’s initialize the routes this way:

Define RouterFull Code
1
2
3
4
5
6
7
8
9
10
11
12

app.Router = Backbone.Router.extend({
routes: {
'*filter' : 'setFilter'
},
setFilter: function(params) {
console.log('app.router.params = ' + params); // just for didactical purposes.
window.filter = params.trim() || '';
app.todoList.trigger('reset');
}
});

Now, you need to initialize it, adding this lines:

Initialize routerFull Code
1
2
3
4
5
6
7
8
9

//--------------
// Initializers
//--------------

+ app.router = new app.Router();
+ Backbone.history.start();
app.appView = new app.AppView();

You can test that you router is working just typing #anything/that/you/want and seeing the parameter in you browser’s console.

2.6.1 Processing the routes

Before rendering the list of items, you need to check the parameters to wether show only the pending ones, or the completed or show them all. As shown in the code snipet below.

Processing the routes in app.AppViewFull Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

@@ -164,7 +177,18 @@
},
addAll: function(){
this.$('#todo-list').html(''); // clean the todo list
- app.todoList.each(this.addOne, this);
+ // filter todo item list
+ switch(window.filter){
+ case 'pending':
+ _.each(app.todoList.remaining(), this.addOne);
+ break;
+ case 'completed':
+ _.each(app.todoList.completed(), this.addOne);
+ break;
+ default:
+ app.todoList.each(this.addOne, this);
+ break;
+ }
},
newAttributes: function(){
return {


If you try adding the words #/pending or #/completed at the end of the URL you’ll get an error!. That’s a good sign, it means the routes are working, but we haven’t implemented the app.todoList.remaining() and app.todoList.completed(). So, that’s next:

Defining completed and remaining functions in app.TodoListFull Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

@@ -85,7 +90,15 @@
//--------------
app.TodoList = Backbone.Collection.extend({
model: app.Todo,
- localStorage: new Store("backbone-todo")
+ localStorage: new Store("backbone-todo"),
+ completed: function() {
+ return this.filter(function( todo ) {
+ return todo.get('completed');
+ });
+ },
+ remaining: function() {
+ return this.without.apply( this, this.completed() );
+ }
});

Now, if you try again adding the hash-tags it will work! But, it will be better if the user can have links to that instead of typing URLs. So, let’s add them.

Show routes' linksFull Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

@@ -32,6 +32,11 @@
<header id="header">
<h1>Todos</h1>
<input id="new-todo" placeholder="What needs to be done?" autofocus>
+ <div>
+ <a href="#/">show all</a> |
+ <a href="#/pending">show pending</a> |
+ <a href="#/completed">show completed</a>
+ </div>
</header>
<section id="main">
<ul id="todo-list"></ul>


Well, that’s all! If completed these 4 parts tutorial you will be familiar with the main Backbone modules (Models, Collections, Views, Events, and Routes). To increase you knowledge you can follow the following resources:

What’s next?

Write a server API in NodeJS to apply the learned here:

Now, do a Todo app in AngularJS:

Hope it was helpful!