Skip to content

Instantly share code, notes, and snippets.

@mwarman
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwarman/9b6e5fc26678de943824 to your computer and use it in GitHub Desktop.
Save mwarman/9b6e5fc26678de943824 to your computer and use it in GitHub Desktop.
Using Google Analytics in a Backbone or Marionette Application
This Gist illustrates how to use Google Analytics with a Backbone or Marionette application router.
The code is described in detail in this YouTube video: http://youtu.be/ElMT7ChrQ9M
Visit leanstacks.com for more information.
# Create the Application
window.SkeletonApp = new Backbone.Marionette.Application
# Navigate to a route
SkeletonApp.navigate = (route, options) ->
options || ( options = {} )
Backbone.history.navigate route, options
if not options.trigger
SkeletonApp.trackPage()
# Handle Backbone History 'route' Events
Backbone.history.on 'route', (router, route, params) ->
SkeletonApp.trackPage()
# Send Page Tracking Data to Google Analytics
# https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
SkeletonApp.trackPage = ->
if ga?
page = Backbone.history.root + Backbone.history.fragment
ga 'send', 'pageview', page
<html>
<body>
<section id="header"></section>
<section id="main"></section>
<section id="footer"></section>
<!-- ... -->
<script src="assets/app/js/app-templates-1.0.0.js"></script>
<script src="assets/app/js/app-1.0.0.min.js"></script>
<!-- Add Google Analytics JavaScript at Bottom of Page Body -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-12345678-1', 'auto');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment