How Do I Track Router Change Events In Backbone.js
Solution 1:
I know this is an old post, but like @kirk suggested, Backbone.js already has it built it.
Backbone.history.on("all", function (route, router) {
//console.log(window.location.hash);
});
I think you'd be better off using this method.
Solution 2:
@qwertymk was half way there. You can look for the hashchange event on the window object:
// jQuery example
$(window).bind('hashchange', function(){
console.log(window.location.hash);
});
Solution 3:
put this somewhere top in your code
Backbone.History.prototype.navigate = _.wrap(Backbone.History.prototype.navigate, function(){
// Get arguments as an arrayvar args = _.toArray(arguments);
// firs argument is the original functionvar original = args.shift();
// Set the before eventBackbone.history.trigger('before:url-change', args);
// Call original functionvar res = original.apply(this, args);
// After eventBackbone.history.trigger('url-changed');
// Return original resultreturn res;
});
the code above will wrap History.navigate function and will trigger "before:url-change" and "url-changed" when it is called
Later you can use
Backbone.history.bind('before:url-change', function(path,e){
console.log("before url change", path, e)
});
Solution 4:
There is another, "Backbone.history.on('route', ...)" event, that works too and you can find it being triggered in the library):
Backbone.history.on('route', function() { debugger; });
It is more precise, because 'all' is a catch all: Quote from Backbone documentation:
Trigger one or many events, firing all bound callbacks. Callbacks are passed the same arguments as
triggeris, apart from the event name (unless you're listening on"all", which will cause your callback to receive the true name of the event as the first argument).
By the way, Backbone best practice is to use listenTo method, e.g.:
myView.listenTo(Backbone.history, 'route', function() { debugger; })
This way you don't need to clean up the event listener manually - instead it is logically bound to the view/model/etc. that uses it.
Post a Comment for "How Do I Track Router Change Events In Backbone.js"