Forward Advance Learning

Routing

Backbone Routing allows you to hook nicely into the address bar at the top of your browser. When the URL changes, Backbone events are fired that we can hook into.

We create a router like this:

var AppRouter = Backbone.Router.extend({
routes: {
"": "home",
"about": "about"
}
});
var router = new AppRouter();

We can then configure to the router:

var AppRouter = Backbone.Router.extend({
routes: {
"cats": "catsRoute",
},
catsRoute: function() {
app.view.render("cats route");
}
});

We can also pass parameters through to our routes:

app.Router = Backbone.Router.extend({
routes: {
"cat/:id": "catRoute"
},
catRoute: function(id) {
app.view.render("cat: " + id);
}
});

Exercise - Hello / Goodbye

Create a view that will show either the word Hello, or the word Goodbye.

Add two hyperlinks to the top of the page for /#hello and /#goodbye. Make it so when I click the links, the view displays hello or goodbye.

Exercise - Sorting

Create /#cats/by-name and #cats/by-age routes and add hyperlinks so you can visit them.

Now Make it so that when you click one or the other of them, the catsList is sorted either by name or by age.

Exercise - Update the URL

Update your cat app so that when you search, the URL is updated. Visiting that URL again brings up the same search.

Reading

Read the router docs here: http://backbonejs.org/#Router

Further reading

If you're interested in PushState, which is the future of web applications, read the Router and History sections in the backbone source: http://backbonejs.org/docs/backbone.html#backbone-router