03.09.2015 Views

Design Patterns

Download - Assembla

Download - Assembla

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

100<br />

CHAPTER 7 ■ THE FACTORY PATTERN<br />

Ajax request in your code, it makes sense to abstract this object creation code into a class and<br />

to create a wrapper for the different steps it takes to actually make the request. A simple factory<br />

works very well here to create an instance of either XMLHttpRequest or ActiveXObject,<br />

depending on the browser’s capabilities:<br />

/* AjaxHandler interface. */<br />

var AjaxHandler = new Interface('AjaxHandler', ['request', 'createXhrObject']);<br />

/* SimpleHandler class. */<br />

var SimpleHandler = function() {}; // implements AjaxHandler<br />

SimpleHandler.prototype = {<br />

request: function(method, url, callback, postVars) {<br />

var xhr = this.createXhrObject();<br />

xhr.onreadystatechange = function() {<br />

if(xhr.readyState !== 4) return;<br />

(xhr.status === 200) ?<br />

callback.success(xhr.responseText, xhr.responseXML) :<br />

callback.failure(xhr.status);<br />

};<br />

xhr.open(method, url, true);<br />

if(method !== 'POST') postVars = null;<br />

xhr.send(postVars);<br />

},<br />

createXhrObject: function() { // Factory method.<br />

var methods = [<br />

function() { return new XMLHttpRequest(); },<br />

function() { return new ActiveXObject('Msxml2.XMLHTTP'); },<br />

function() { return new ActiveXObject('Microsoft.XMLHTTP'); }<br />

];<br />

for(var i = 0, len = methods.length; i < len; i++) {<br />

try {<br />

methods[i]();<br />

}<br />

catch(e) {<br />

continue;<br />

}<br />

// If we reach this point, method[i] worked.<br />

this.createXhrObject = methods[i]; // Memoize the method.<br />

return methods[i];<br />

}<br />

// If we reach this point, none of the methods worked.<br />

throw new Error('SimpleHandler: Could not create an XHR object.');<br />

}<br />

};

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!