可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I need to run a function every time the application switches URLs in Backbone.js, and I need to know the hashtag the URL has changed to. I'm assuming there is an event that I can bind to but I haven't been able to figure out which event and what object to bind to.
Specifically I want to ship the new URL to an analytics application.
回答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.
回答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); });
回答3:
put this somewhere top in your code
Backbone.History.prototype.navigate = _.wrap(Backbone.History.prototype.navigate, function(){ // Get arguments as an array var args = _.toArray(arguments); // firs argument is the original function var original = args.shift(); // Set the before event Backbone.history.trigger('before:url-change', args); // Call original function var res = original.apply(this, args); // After event Backbone.history.trigger('url-changed'); // Return original result return 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) });
回答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 trigger
is, 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.