Skip to content

Instantly share code, notes, and snippets.

@Emiel45
Created October 9, 2014 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Emiel45/070e18635c7f39550cb3 to your computer and use it in GitHub Desktop.
Save Emiel45/070e18635c7f39550cb3 to your computer and use it in GitHub Desktop.
var reqs = [];
window.jsonp_handler = function(id, res) {
reqs[id].handle(res);
};
function Req(url, data, handler) {
this.url = url;
this.data = typeof data == "object" ? data : {};
this.handler = handler;
this.id = Math.ceil(Math.random() * 10000).toString();
this.timeoutTimer = setTimeout(this.onTimeout.bind(this), 2000);
var args = "";
for (var k in this.data) {
var v = this.data[k];
args += "&" + encodeURIComponent(k) + "=" + encodeURIComponent(v);
}
this.script = document.createElement("script");
this.script.type = "text/javascript";
this.script.src = this.url + "?p=" + this.id + args;
document.body.appendChild(this.script);
reqs[this.id] = this;
}
Req.prototype.onTimeout = function() {
this.delete();
};
Req.prototype.delete = function() {
delete reqs[this.id];
clearTimeout(this.timeoutTimer);
this.script.remove();
};
Req.prototype.handle = function(res) {
this.delete();
var data;
if (this.handler && (data = this.handler(res))) {
new Req(this.url, data, this.handler);
}
};
module.exports = function(url, data, handler) {
return new Req(url, data, handler);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment