Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I track router change events in Backbone.js

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.

like image 826
Thomas Hunter II Avatar asked Jan 12 '12 19:01

Thomas Hunter II


2 Answers

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.

like image 124
Theus G Avatar answered Oct 11 '22 09:10

Theus G


@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);
});
like image 34
Thomas Hunter II Avatar answered Oct 11 '22 08:10

Thomas Hunter II