Skip to content

Instantly share code, notes, and snippets.

@prettycode
Last active December 17, 2015 15:29
Show Gist options
  • Save prettycode/5632141 to your computer and use it in GitHub Desktop.
Save prettycode/5632141 to your computer and use it in GitHub Desktop.
Simple wrapper for Google Analytics. Experimental instance pattern.
function Analytics(config) {
config = config || {};
var ga = (_gaq || []),
accountKey,
domainName,
proto = (this.prototype = Object.prototype);
proto.accountKey = function() {
if (!arguments.length) {
return accountKey;
}
else {
accountKey = arguments[0];
ga.push(['_setAccount', accountKey]);
return this;
}
};
if (config.accountKey) {
proto.accountKey(config.accountKey);
}
proto.domainName = function() {
if (!arguments.length) {
return domainName;
}
else {
domainName = arguments[0];
ga.push(['_setDomainName', domainName]);
return this;
}
};
if (config.domainName) {
proto.domainName(config.domainName);
}
proto.trackEvent = function(name, value) {
ga.push(['_trackEvent', name, value]);
return this;
};
proto.trackPageView = function(path) {
if (typeof path === 'undefined') {
path = window.location.pathname;
}
ga.push(['_trackPageview', path]);
return this;
};
}
_gaq = {
push: function() {
console.log(JSON.stringify(arguments));
}
};
var analytics = new Analytics({
accountKey: 'UA-65432-1'
});
analytics
.trackPageView()
.trackPageView('/account/status')
.trackEvent()
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment