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
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:
#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.
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:
Now, you need to initialize it, adding this lines:
You can test that you router is working just typing
#anything/that/you/want and seeing the parameter in you browser’s console.
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.
If you try adding the words
#/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.completed(). So, that’s next:
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.
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:
Write a server API in NodeJS to apply the learned here:
Now, do a Todo app in AngularJS:
Hope it was helpful!