Skip to content

Instantly share code, notes, and snippets.

@rnagle
Created December 7, 2011 21:34
Show Gist options
  • Save rnagle/1444767 to your computer and use it in GitHub Desktop.
Save rnagle/1444767 to your computer and use it in GitHub Desktop.
Chartbeat.js
var Chartbeat = function(opts) {
if (!opts)
throw new Error("Chartbeat: Please specify an api key and host!");
if (!opts.api_key)
throw new Error("Chartbeat: Please specify an api key!");
if (!opts.host)
throw new Error("Chartbeat: Please specify a host!");
this.creds = {
api_key: opts.api_key,
host: opts.host,
}
// Placeholders
this.data = {
data: null,
previous_data: null
}
this.tmp = {};
this.uid = "chartbeat_" + Math.floor(Math.random()*100000000);
// Default callback.
// This always runs, saving the response from Chartbeat in this.data
this.successful_fetch = function(data) {
if (data.error)
throw new Error(data.error);
this.data.previous_data = this.data.data;
this.data.data = data
this.utils.cleanup_window(this.uid);
return this;
}
this.fetch = function(type, callback, type_opts) {
/* Parameters:
*
* type (string): 'pages', 'pathsummary', 'recent', 'quickstats',
* 'toppages'; required.
*
* callback (function): function to wrap json
* response from chartbeat; optional.
*
* type_opts (object): required for some types; example for
* 'pathsummary' type: {"path":"/", "keys":"a", "types":"s"}
*/
window[this.uid] = this;
if (!callback) {
this.tmp.callback_str = "window['" + this.uid + "'].successful_fetch";
}
if (typeof callback == 'function') {
this.tmp.callback = this.utils.bind(this, function(data) {
if (data.error)
throw new Error(data.error);
callback(data);
this.successful_fetch(data);
});
this.tmp.callback_str = "window['" + this.uid + "'].tmp.callback";
}
var fetch_options = {
"apikey": this.creds.api_key,
"host": this.creds.host,
"jsonp": this.tmp.callback_str
}
var params = this.utils.parameterize(fetch_options);
var url = "http://api.chartbeat.com/"+type+"/?"+params;
if (type_opts) {
params = params + this.utils.parameterize(type_opts);
url = "http://api.chartbeat.com/"+type+"/?"+params;
}
var script = document.createElement("script");
script.src = url;
if (document.body.appendChild(script))
return true;
else
return false;
}
this.utils = {
bind: function(obj, func) {
return function() {
return func.apply(obj, arguments);
}
},
// URL parameter string from literal object
parameterize: function(params) {
var str = '';
for (param in params) {
str += param + "=" + escape(params[param]) + "&";
}
str.replace(/\&$/, '');
return str;
},
// Get rid of temporary global
cleanup_window: function(str) {
for (var v in window) {
if (v == str) {
delete window[v];
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment