Being able to intercept a certain operation to an object can be really useful, in particular during a troubleshooting session. With ECMAScript 6, this is possible via its new feature, proxy. Creating a proxy on a particular object allows a predefined handler to get notified when something happens.
In the latest draft specification (Rev 15, May 14, 2013), section 15.18 on Proxy Objects is still empty. It is safe to assume that more information will be available later, when the specification starts to stabilize. Meanwhile, there is some useful information on the Direct Proxies wiki page. At the time of this writing, proxy support is already available on the latest stable version of Firefox and Chrome (experimental flag needs to be enabled).
The best way to illustrate a proxy is by a simple example (note: the code fragment is updated to use the new syntax, Proxy(target, handler)
, and not the deprecated Proxy.create
):
var engineer = { name: 'Joe Sixpack', salary: 50 };
var interceptor = {
set: function (receiver, property, value) {
console.log(property, 'is changed to', value);
receiver[property] = value;
}
};
engineer = Proxy(engineer, interceptor);
In the above code, we create a simple object engineer
. This object will be replaced by another one as the result of installing a proxy via Proxy()
. The second parameter for this function is denoting a handler, interceptor
in our case. A handler can have many different functions, for this simple example we have only one, set
.
Let’s see what happens if we executed the following code:
engineer.salary = 60;
The handler will be called and its set
function will be invoked. Thus, we will get:
salary is changed to 60
Every time a property of engineer
is set, our interceptor will know about it. Obviously, there are various other operations which can be detected a proxy handler, such as property getter, keys()
, iterator, and many others. Refer to the Direct Proxies wiki page for more details. Note: you might be also interested in tvcutsem/harmony-reflect which contains the polyfills so that you can use the new Proxy API on top of the deprecated one.
Beside for debugging purposes, proxy can be helpful for libraries which implement data binding. Because a handler can be hooked to the data model, there is no need to use an alternative syntax (e.g. explicit set
to change a value) or to continuously track the change (e.g. dirty state) to modify the model.
How would you plan to use proxy?