How do I track router change events in Backbone.js

流过昼夜 提交于 2020-01-22 09:24:46

问题


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.



来源:https://stackoverflow.com/questions/8841418/how-do-i-track-router-change-events-in-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!