Tracking Backbone.js "Page Views" with Mixpanel

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 is the author of Advanced Microservices and is a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.