Backbone routers
Routers are a common way for web frameworks to translate a URL to an action. On backbone they are used when creating single page applications to refresh the content of the page without actually refreshing the page.
Lets see an example of how they work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
var MyAppRouter = Backbone.Router.extend({
// Define the routes we want to listen to
routes: {
'': 'indexAction',
'main': 'mainAction',
'listing/:page': 'listingAction',
'profile/:id(/:username)': 'profileAction',
'anything/*all': 'anythingAction'
},
// Acts as a constructor
initialize: function() {
console.log('Router started');
},
indexAction: function() {
console.log('Index action');
},
// Now we list our router actions
mainAction: function() {
console.log('Main page');
},
listingAction: function(page) {
console.log('Show page ' + page);
},
profileAction: function(id, username) {
console.log('You passed id: ' + id + ' and username: ' + username);
},
anythingAction: function(all) {
console.log(all);
}
});
// We need to instantiate it
var router = new MyAppRouter();
// This tells backbone to start listening for URL changes
Backbone.history.start();