How to Add Google Analytics Page Tracking to Your Backbone.js App
by Dave Augustine
A few weeks ago we launched a new mobile version of Airbnb that was built with Backbone.js and CoffeeScript. Over the next few weeks we'll be posting about our experience and sharing a bunch of the code we wrote.
To kick things off, let's start short and simple and talk about page tracking.
Step 1. The Only Step
Open up your Router and add the following to your initialize function and add the _trackPageview function:
CoffeeScript not your cup of tea? Here's the JavaScript.
A More Thorough Explanation:
Tracking your page views is a pretty basic requirement and is dead simple with Google Analytics (GA); make a free account, drop in their script and set some variables and you are good to go. It's not quite that straight forward when you only load one html page and the rest via JavaScript, but it can be close.
Take a look at the gist above and let's break it down.
What's going on here? In your Router's initialize function we are a binding to any routing event that is fired and calling the _trackPageView function. In Backbone, a route event is fired anytime there is a match on the routes you define. This allows you to execute code based on the current state of the URL.
For example, if you had a router like this:
This entry matches a URL with the form: http://m.airbnb.com/#listing/86456 and would call the listing function found within the router. This function also accepts id as a parameter so we can load the appropriate listing data.
Inside the _trackPageView function we are grabbing the 'current page' from the Backbone history manager - this will return the proper fragment regardless of whether you've opted in to pushState or not. GA provides a queue to push page tracking events via a function also named _trackPageView. This is normally called all by its lonesome on page load which adds whatever the current URL is to analytics. You can push this call onto the analytics queue manually with an additional parameter to name the page you are tracking provided it starts with a / character.
Putting it all together: all we have to do is grab that fragment, prepend a "/" and push it into the queue. GA takes care of the rest. Check out your GA dashboard. You should be seeing pages tracked in the form of /login or /listings/86456 or whatever awesome URLs your app uses.
Happy coding and more to come!
