This tutorial is about BackboneJS Routes.
BackboneJS Tutorial series:
- Backbone.js for Absolute Beginners - Getting started (Part 1: Intro)
- Backbone.js for absolute beginners - getting started (part 2: Models, Collections and Views)
- Backbone.js for absolute beginners - getting started (part 3: CRUD)
- 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:
1 |
|
Now, you need to initialize it, adding this lines:
1 |
|
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.
1 |
|
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:
1 |
|
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.
1 |
|
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!