
Untitled
By: a guest on
May 7th, 2012 | syntax:
None | size: 1.54 KB | hits: 16 | expires: Never
(function(exports, document) {
var tmpl = function tmpl(s,d){return s.replace(/:([a-z]+)/g, function(w,m){return d[m];});},
uid = 0,
api = 'https://api.github.com/',
// request
// Load JSON from a server in a different domain (JSONP)
//
// *Arguments:*
//
// * url — with placeholder in the form of :placeholder
// * params — hash of parameters value, the property name is used to match placeholder to replace url with proper value.
// * callback - gets called with an error object (null if success) and data.
//
// *Example:*
//
// request('/repos/:user/:repo/git/trees/:sha?recursive=1')
//
request = function request(url, params, callback) {
var jsonpString = 'jsonp' + (++uid),
script = document.createElement('script'),
delim = /\?/.test(url) ? '&' : '?',
head = request.head ? request.head : (request.head = $('head'));
if(!callback) {
callback = params;
params = {};
}
exports[jsonpString] = function(response) {
var data = response.data,
meta = response.meta;
if(meta.status !== 200) {
return callback({error: data.message, status: meta.status});
}
callback(null, data);
delete window[jsonpString];
};
// clean trailing slash url
url = url.replace(/^\//, '');
params.callback = jsonpString;
script.src = tmpl(api + url + delim + 'callback=:callback', params);
head.append(script);
};
request.callbacks = [];
exports.request = request;
})(this, this.document);