Tracking Backbone.js "Page Views" with Mixpanel

Multithreaded JavaScript has been published with O'Reilly!

At the startup I was working with recently, I was tasked with getting the different “Page Views” in Backbone.js to be sent to Mixpanel as different page views. Backbone doesn't use normal page views, since it's a Single Page Application framework. Page view events are only triggered by the Mixpanel javascript library during a page view.

After talking with the Mixpanel customer support, I found out I can track an event called mp_page_view, which is the event Mixpanel treats internally as a page view. It has one attribute, and that is mp_page, which is the URL to the page being viewed. This is relative to the root of your site. Unfortunately, if you use the # symbol, Mixpanel ignores the hit, so it has to be removed. This means that from within the Mixpanel screens, you can't click a link to go to the equivalent page in your app. But, this isn't really to big of a deal.

Backbone, since it uses the hashchange API, is really easy to integrate with. The following code works assuming you are using jQuery as your Backbone selector engine (I'm not sure if it works with Zepto). Just throw this code somewhere in your JavaScript, make sure it comes after jQuery, Backbone, and Mixpanel code has been instantiated.

$(window).bind('hashchange', function() {
  mpq.track("mp_page_view", {
    mp_page: window.location.href.replace(/#/, '')
  });
});

And there you have it! Let me know in the comments below if this doesn't work for you or if you try it with Zepto.

Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.