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.

210<br />

CHAPTER 14 ■ THE PROXY PATTERN<br />

if(!this.initialized) {<br />

return;<br />

}<br />

return this.directory.showPage(page);<br />

}<br />

};<br />

Blocking calls to showPage is easy; you simply query the initialized attribute. If it is true,<br />

you can invoke the real subject’s method. Showing a warning message while the object loads is<br />

a little trickier. How can you know when the class is truly finished loading? It is possible for the<br />

real subject to create a custom event that the proxy can subscribe to, but in this example, we<br />

used a simpler technique. The currentPage attribute is only set after the data has loaded. Simply<br />

query that attribute every 100 milliseconds until you find that it has been set. At that point,<br />

remove the loading message and mark the object as initialized.<br />

The virtual proxy is now complete. This is a very simple example of how this type of proxy<br />

can work. A more complex version could implement more robust initialization checks and<br />

more accurate triggers. Each proxy will vary depending on the exact user interaction you are<br />

expecting. Next we will cover a dynamic virtual proxy that can be used as a template for creating<br />

your own proxy in the future.<br />

General Pattern for Creating a Virtual Proxy<br />

JavaScript is an enormously flexible language. Because of this, you can create a dynamic virtual<br />

proxy that will examine the interface of the class given to it, create its own corresponding methods,<br />

and defer instantiation of that class until some set condition is reached. To create this<br />

dynamic proxy, first create the shell of the class and the _initialize and _checkInitialization<br />

methods. This class is abstract; it will need to be subclassed and configured to work properly:<br />

/* DynamicProxy abstract class, incomplete. */<br />

var DynamicProxy = function() {<br />

this.args = arguments;<br />

this.initialized = false;<br />

};<br />

DynamicProxy.prototype = {<br />

_initialize: function() {<br />

this.subject = {}; // Instantiate the class.<br />

this.class.apply(this.subject, this.args);<br />

this.subject.__proto__ = this.class.prototype;<br />

var that = this;<br />

this.interval = setInterval(function() { that._checkInitialization(); }, 100);<br />

},<br />

_checkInitialization: function() {<br />

if(this._isInitialized()) {<br />

clearInterval(this.interval);<br />

this.initialized = true;<br />

}

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

Saved successfully!

Ooh no, something went wrong!