Skip to content

Instantly share code, notes, and snippets.

@roothybrid7
Created October 1, 2011 01:12
Show Gist options
  • Save roothybrid7/1255461 to your computer and use it in GitHub Desktop.
Save roothybrid7/1255461 to your computer and use it in GitHub Desktop.
XHR Object Pool pattern
// You would use this object as follows:
var xhr = XHRFactory.getInstance();
var url = "http://www.xyz.com/someresource/....";
// do the operation
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState==4) {
// if "OK"
if (xhr.status==200) {
// process the response
}
XHRFactory.release(xhr);
}
};
xhr.send("");
//XHRFactory.release()
var XHRFactory = (function(){
// static private member
var stack = new Array();
var poolSize = 10;
var nullFunction = function() {}; // for nuking the onreadystatechange
// private static methods
function createXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject('Microsoft.XMLHTTP')
}
}
// cache a few for use
for (var i = 0; i < poolSize; i++) {
stack.push(createXHR());
}
// shared instance methods
return ({
release:function(xhr){
xhr.onreadystatechange = nullFunction;
stack.push(xhr);
},
getInstance:function(){
if (stack.length < 1) {
return createXHR();
} else {
return stack.pop();
}
},
toString:function(){
return "stack size = " + stack.length;
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment