Last active
August 29, 2015 13:56
-
-
Save jimmyhillis/9167577 to your computer and use it in GitHub Desktop.
A google analytics wrapper for safe callbacks and tracking
This file contains 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
var Tracker = (function () { | |
var Tracker = function (options) { | |
options = options || {}; | |
this.debug = options.debug || false; | |
this.timeout = options.timeout || 600; | |
return this; | |
}; | |
Tracker.prototype.send = function (type, post) { | |
if (window.ga) { | |
ga('send', type, post); | |
} | |
this._debug('send', type, post); | |
} | |
Tracker.prototype.event = function (category, action, label, value, callback) { | |
var post = { | |
eventCategory: category, | |
eventAction: action, | |
eventLabel: label, | |
eventValue: value, | |
hitCallback: this.callbackFallback(callback) | |
} | |
this.send('event', post); | |
}; | |
Tracker.prototype.view = function (path, title, callback) { | |
var post = { | |
page: path || null, | |
title: title || null, | |
hitCallback: this.callbackFallback(callback) | |
}; | |
this.send('pageview', post); | |
}; | |
Tracker.prototype.callbackFallback = function (callback) { | |
var self = this | |
, is_done = false; | |
if (typeof callback !== 'function') { | |
return null; | |
} | |
setTimeout(function () { | |
if (!is_done) { | |
is_done = true; | |
callback(); | |
} | |
}, this.timeout); | |
return function () { | |
if (!is_done) { | |
is_done = true; | |
callback(); | |
} | |
} | |
}; | |
Tracker.prototype._debug = function () { | |
if (this.debug && window.console && window.console.log) { | |
window.console.log(arguments); | |
} | |
} | |
return Tracker; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment