Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.54 KB  |  hits: 16  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. (function(exports, document) {
  2.  
  3.   var tmpl = function tmpl(s,d){return s.replace(/:([a-z]+)/g, function(w,m){return d[m];});},
  4.   uid = 0,
  5.   api = 'https://api.github.com/',
  6.  
  7.   // request
  8.   // Load JSON from a server in a different domain (JSONP)
  9.   //
  10.   // *Arguments:*
  11.   //
  12.   // * url — with placeholder in the form of :placeholder
  13.   // * params — hash of parameters value, the property name is used to match placeholder to replace url with proper value.
  14.   // * callback - gets called with an error object (null if success) and data.
  15.   //
  16.   // *Example:*
  17.   //
  18.   //     request('/repos/:user/:repo/git/trees/:sha?recursive=1')
  19.   //
  20.   request = function request(url, params, callback) {
  21.     var jsonpString = 'jsonp' + (++uid),
  22.     script = document.createElement('script'),
  23.     delim = /\?/.test(url) ? '&' : '?',
  24.     head = request.head ? request.head : (request.head = $('head'));
  25.    
  26.     if(!callback) {
  27.       callback = params;
  28.       params = {};
  29.     }
  30.    
  31.     exports[jsonpString] = function(response) {
  32.       var data = response.data,
  33.       meta = response.meta;
  34.      
  35.       if(meta.status !== 200) {
  36.         return callback({error: data.message, status: meta.status});
  37.       }
  38.      
  39.       callback(null, data);
  40.       delete window[jsonpString];
  41.     };
  42.    
  43.     // clean trailing slash url
  44.     url = url.replace(/^\//, '');
  45.    
  46.     params.callback = jsonpString;
  47.     script.src = tmpl(api + url + delim + 'callback=:callback', params);
  48.     head.append(script);
  49.   };
  50.  
  51.   request.callbacks = [];
  52.  
  53.  
  54.   exports.request = request;
  55.  
  56.  
  57. })(this, this.document);