Created
February 8, 2012 18:33
-
-
Save daveaugustine/1771986 to your computer and use it in GitHub Desktop.
Super simple Google Analytics page tracking with backbone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
initialize: -> | |
@bind 'all', @_trackPageview | |
_trackPageview: -> | |
url = Backbone.history.getFragment() | |
_gaq.push(['_trackPageview', "/#{url}"]) |
@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.
Three things:
_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}");
- 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)
- 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
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: