Proxy

An object representing another object.

jQuery makes limited use of the Proxy pattern.



Overview


The Proxy Pattern is an object that stands-in or represents another object. Searching for the keyword proxy in jQuery source file leads to a proxy method. This method takes a function and returns a new one which will always have a particular context (i.e., the this value in the function). The returned function is the proxy function object.

This is helpful in event handlers where there is a delay between calling and executing the event handler (and you don't want the overhead of building a closure). Consider the example below:

<div id="area" class="red"></div>

$("#area").on("click", function (e) {
    $(this).toggleClass("yellow");
});

Click repeatedly on the area to see the effect.

Clicking the div element will toggle the area between red and yellow. The $(this) element refers to the element that was just clicked. Now, we wish to automate the toggling by using setInterval. Unfortunately this attempt fails:

<div id="area" class="red"></div>

$("#area").on("click", function (e) {
    setInterval(function() {
        $(this).toggleClass("yellow");       
    }, 1000); 
});

Because of the delay, the function's context has changed and the $(this) value refers to the global window object. This is where the proxy method comes in. We create a proxy function that remembers (using its closure) the original $(this) context when it was first called. Now setInterval will call the proxy rather than the original function. Here is what this looks like:

<div id="area" class="red"></div>

$("#area").on("click", function (e) {
    setInterval($.proxy(function () {
        $(this).toggleClass("yellow");
    }, this), 1000);
});

Click on the area to start the process.

After the first click, the area toggles between red and yellow indefinitely (we did not build in a stop).

Note that you could have also solved the above problem by maintaining the original this value in a closure, like so:

<div id="area" class="red"></div>

$("#area").on("click", function (e) {
    var that = this;
    setInterval(function () {
        that.toggleClass("yellow");
    }, 1000);
});

Fortunately, this feature has been standardized in ES5 (EcmaScript 5) in the form of the bind method (which was borrowed from the Prototype framework). It's an elegant way to assign and memorize a context to a function. Most modern browsers support it. Here is how it is used:

<div id="area" class="red"></div>

$("#area").on("click", function (e) {
    setInterval(function () {
        $(this).toggleClass("yellow");    
    }.bind(this), 1000);
});

The bind function creates a new function that, when called, has its this keyword set to the provided value. This is the proxy function that stands-in for the original function.



  Observer
Façade