Skip to content

Instantly share code, notes, and snippets.

@daveaugustine
Created February 8, 2012 18:33
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save daveaugustine/1771986 to your computer and use it in GitHub Desktop.
Save daveaugustine/1771986 to your computer and use it in GitHub Desktop.
Super simple Google Analytics page tracking with backbone
initialize: ->
@bind 'all', @_trackPageview
_trackPageview: ->
url = Backbone.history.getFragment()
_gaq.push(['_trackPageview', "/#{url}"])
@timherby
Copy link

Thanks for posting this. BTW, if your application is not loaded at the root of the site, you'll need to switch to the following:

    url = Backbone.history.root + Backbone.history.getFragment()
    _gaq.push(['_trackPageview', url])

@uniqname
Copy link

@bind 'all' will fire on a route event and a route:routename event, thus logging a pageview twice. Using @bind 'route' seems to solve that problem.

@peteratticusberg
Copy link

Three things:

  1. _gaq is a method from ga.js. As of right now, google is trying to get everyone to switch from using ga.js + "google analytics classic" to using analytics.js + "Universal Analytics". If you're using analytics.js the line

_gaq.push(['_trackPageview', "/#{url}"])

should read

ga('send', 'pageview', "/#{url}");

  1. Rather than inserting the above code into every router in your application, you might find it easier to simply bind a "route" event to the Backbone.history object. This fires once every time any route is matched. To do this, you just need the line

Backbone.history.on("route", sendPageview)

  1. Make sure that when you're looking at the "real time" google analytics screen when checking to see if your code is working, as all other reporting takes up to 24 hours to show up.

Also, if you want to test on localhost, make sure in that you specify 'auto' in your call to ga('create', ...). e.g. ga('create', 'auto') as opposed to ga('create', 'mysite.com')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment