Watch if an object has changed

150 Views Asked by At

Is it possible to execute some code each time an object has changed ?

var a = {x: 12, y: 63};

a.watch(function () { console.log('The object has changed!'); });

a.x = 16;   // The object has changed!
a.y = 1;   // The object has changed!

It seems to be available on Firefox only: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch

How is it possible to achieve this in JavaScript / node.js? (if possible, without using a getter/setter method)

1

There are 1 best solutions below

2
On

You can use Object Observe... it's experimental so proceed with caution...

var obj = {
    foo: 0,
    bar: 1
};

Object.observe(obj, function(changes) {
    console.log(changes);
});

obj.baz = 2;