In a Backbone JS project, I am trying to listen for events emitted by the router. From the docs:
When the visitor presses the back button, or enters a URL, and a particular route is matched, the name of the action will be fired as an event, so that other objects can listen to the router, and be notified.
Unfortunately, I can't get this to work, no matter if I use on
or listenTo
to listen for the router events.
The router looks like this:
var appRouter = Backbone.Router.extend({
routes: {
'' : 'index',
'page(/:id)' : 'showPage'
}
});
app.Router = new appRouter();
Backbone.history.start();
An in a view's initialize function, I try to listen for the events like this:
initialize: function () {
this.listenTo(app.Router, 'route:showPage', this.myTestFn);
app.Router.on('route:index', this.myTestFn);
},
To me, this looks correct, but myTestFn
is never called.
How do I listen for route events in Backbone JS?