Backbone.js trigger function every time the Router is used

It's just interesting if there is an easy way to run a custom function every time the Backbone.js router is used, without having to add it to each of the functions of the router. 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 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?

+7
source share
3 answers

Whenever a route maps to a Router , the route:[name] event fires with the name of the mapped route to allow classes to listen for specific route mappings. All base objects also support the all event, which fires whenever an event occurs.

Thus, you can use this to bind to the all event on the Router , which will fire whenever the router performs some routing.

 initialize: function() { this.bind( "all", this.change ) }, 

If you are interested in a route that matches, it is passed as the first parameter of the associated function.

Read more here in the FAQ

+19
source

More (new) Trunk way to record binding:

 initialize: function() { this.listenTo(this, "all", this.change ) }, 

it would be better to listen simply to route if you ask me; Since all fires two events, I think:

"route: [name]" (params) - started by the router when a specific route matches.
"route" (route, parameters) - triggered by the router when any route has been mapped.

+9
source

I'm new to the spine. After Laurens answer I managed to cause a route change below

 app_router.on('route', function(e){ console.log(e); }); 
0
source

All Articles