Skip to content

Instantly share code, notes, and snippets.

@jimmyhillis
Last active August 29, 2015 13:56
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 jimmyhillis/9167577 to your computer and use it in GitHub Desktop.
Save jimmyhillis/9167577 to your computer and use it in GitHub Desktop.
A google analytics wrapper for safe callbacks and tracking
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