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:

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:

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:

Adrian Mejia is a full-stack web developer working at Cisco in Boston. Currently working at Cisco as a Software Engineer. Adrian enjoys writing books and posts about programming, technologies and nerdy stuff. Find our more here.