Question

I was trying to find some resources online for using Google Analytics' event tracking functionality in a Backbone application, and the only one that I was able to find was a blog post from airbnb, which uses CoffeeScript. Does anyone know of any resources for a regular javascript Backbone app? I have not used the event tracking functionality before, so basic resources are appreciated ...

Thank you!

Was it helpful?

Solution

You can just push events into the queue whenever is appropriate.

So, for example, we have a single paged app, for which we want to track page views, although we're never reloading the page.

To achieve this goal, we attach on all of our router events a listener which pushes each new page view into the _gaq stack. (This is greatly simplified.)

router.on("route", function(page) {
    _gaq.push(['_trackPageview', page]);      
});

This will push the page argument into the Google Analytics tracking stack. Just make sure that you've set up Google Analytics prior to this call.

For events, for example, we sometimes want to track a button being pushed. Therefore, we just make a _trackEvent push into the queue with the object containing the details of what we're pushing.

Instead of putting a ton of _gaq.push code on your page, I would recommend you to make a function available throughout your app that abstracts this functionality, such as:

var track = function(event, payload){
    _gaq.push[event, payload];
};

This will isolate you from changes to the Analytics API, as well as allow you to add other reporting locations to your tracking events easily.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top