Just wondering if there is a simple way to trigger a custom function each time a Backbone.js router is utilized, without having to add it in each of the router functions. Now my script looks like this:
var AppRouter = Backbone.Router.extend({
routes: {
'' : 'index',
'test': 'test',
},
initialize: function() {
},
index: function() {
customFunction();
indexView.render();
},
test: function() {
customFunction();
testView.render();
},
});
I would like to have it something like this:
var AppRouter = Backbone.Router.extend({
routes: {
'' : 'index',
'test': 'test',
},
initialize: function() {
},
index: function() {
indexView.render();
},
test: function() {
testView.render();
},
change: function() {
customFunction();
}
});
Does anyone have any suggestions?
Whenever a route is matched by the Router
, a route:[name]
event is fired with the name of the route matched, to allow classes to listen to certain route matches. All backbone objects also support the all
event which fires whenever an event does.
So you could make use of this to bind to the all
event on the Router
, which will fire whenever the router does some routing.
initialize: function() {
this.bind( "all", this.change )
},
If you were interested in the route that matched, it is passed as the first parameter to the bound function.
More details here in the FAQ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With