ES6 : observe the object change using Proxy

17 Feb 2016

Utilizing ES6 Proxy we can observe a change in object or do some validation before setting an value.

The ES6 Proxy constructor will accept the source object and an interceptor/handler. An interceptor can be a object with a functions which define the operation.

const obj = {};

const handler = {
  set(target, key, value) {
    console.log(`Setting value ${key} as ${value}`)
    target[key] = value;
  },
};

const p = new Proxy(obj, handler);
p.a = 10; // logs "Setting value a as 10"
p.c = 20; // logs "Setting value c as 20"
console.log(p.a); // logs 10

The above snippet is an example for how we can observe a change on obj when a value is set or changed.

Similar way we can observe when we try to read any value from the object by defining a get method on handler.

const obj = {a: 10, c: 20};

const handler = {
  get(target, key) {
    console.log(`Reading value from ${key}`)
    return target[key];
  },
};

const p = new Proxy(obj, handler);
console.log(p.a); // logs "Reading value from a" and "10"

Now to observe deleting a key we can define deleteProperty on handler.

const obj = {a: 10, c: 20};

const handler = {
  deleteProperty(target, key) {
    console.log(`Deleting ${key}`)
    delete target[key];
  },
};

const p = new Proxy(obj, handler);
delete p.a; // logs "Deleting a"

You can find a working sample on jsbin. This is just a basics of Proxy. you can look into more ways to observe on Proxy on MDN

If you particularly enjoy my work, I appreciate donations given with Gittip.