Created
October 1, 2011 01:12
-
-
Save roothybrid7/1255461 to your computer and use it in GitHub Desktop.
XHR Object Pool pattern
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
// 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(""); |
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
//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