I want to highlight the current state of navigation. For example, if hashchange #home , I want to change the Home menu link and other links differently.
Backbone.js fires individual events like route:home , ... route:some-other when you click #home and other links. I have not seen any general event that will be fired for each hash exchange. With this I have to write the logic of state allocation, binding to all the events of the route, which, I think, is not a good solution.
So, I redefined Backbone.Router.route in my class / router object, e.g.
// override backbone' Router.route method to publish // common 'route_change' event for any hash change route : function(route, name, callback) { Backbone.history || (Backbone.history = new Backbone.History); if (!_.isRegExp(route)) route = this._routeToRegExp(route); Backbone.history.route(route, _.bind(function(fragment) { var args = this._extractParameters(route, fragment); callback.apply(this, args); this.trigger.apply(this, ['route:' + name].concat(args)); // ADDED BY: ManiKanta G // name: route method // fragment: route path // args: any additional args this.trigger.apply(this, ['route_change'].concat(name, fragment, args)); }, this)); }
This will post a generic route_change event for each hash exchange and pass name , fragment and other args , with which I isolate the state in one place.
My question is do I need to override the Backbone method, for example, or is there some kind of build mechanism that I can use here. If not, I would like to see similar behavior in Backbone.js
Edit: sample program
Router = Backbone.Router.extend({ routes : { '': 'root', 'home': 'home', 'about':'about' }, // app routing methods root: function () { console.log('root route'); }, home: function () { console.log('home route'); }, about: function () { console.log('about route'); } }); Router.bind('all', function () { console.log('all route...'); }); router = new Router();
and using the router described above:
router.navigate('home', true);
output: home route
Update on why the above program does not work:
we must bind the all event to the Router instance , but not to the Router itself, so changing Router.bind('all', ... to router.bind('all', ...) will do the above program