Created
April 7, 2009 18:18
-
-
Save audionerd/91370 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// JSONP.Request for Prototype | |
// based on: http://github.com/kangax/protolicious/blob/master/get_json.js | |
JSONP = { count: 0 }; | |
JSONP.Request = Class.create({ | |
initialize: function(url, options) { | |
this.options = { | |
timeoutInSeconds: 5, | |
onSuccess: Prototype.emptyFunction, | |
onFailure: Prototype.emptyFunction | |
}; | |
Object.extend(this.options, options || { }); | |
this.request(url, this.options.onSuccess, this.options.onFailure); | |
}, | |
request: function(url, callbackfn, failurefn) { | |
this.global = window; | |
this.script = document.createElement('script') | |
this.token = '__jsonp'+JSONP.count; | |
this.head = $$('head')[0]; | |
this.timeoutId = this.onTimeOut.bind(this).delay(this.options.timeoutInSeconds); | |
// e.g.: global[__jsonp0] = callbackfn function(){} | |
this.global[this.token] = callbackfn; | |
// look for "?" parameter in the url, replace it with new unique callback | |
this.script.src = url.replace( /\?(&|$)/, this.token + '$1'); // the '$1' is to add back in & that are excluded in the regex | |
// clean up on load: remove script tag, null script variable and delete global callback function | |
this.script.onload = this.onScriptLoad.bind(this); | |
this.head.appendChild(this.script); | |
// callback name should be unique | |
JSONP.count++; | |
}, | |
onScriptLoad: function() { | |
this.cleanup(); | |
}, | |
onTimeOut: function() { | |
this.script.onload = null; | |
this.cleanup(); | |
if (this.options.onFailure) this.options.onFailure(); | |
}, | |
cleanup: function() { | |
clearTimeout(this.timeoutId); | |
this.timeoutId = null; | |
this.script.remove(); | |
this.script = null; | |
delete this.global[this.token]; // callback has served it's purpose -- remove it | |
} | |
}); | |
// EXAMPLE | |
// new JSONP.Request( | |
// "http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", | |
// { | |
// timeoutInSeconds: 5, | |
// onSuccess: function(data) { | |
// console.log(data.items.pluck('title').join('\n')) | |
// }, | |
// onFailure: function() { | |
// console.log("Error loading JSONP.Request"); | |
// } | |
// } | |
// ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment