2

I am looking for a cross-browser method allowing me to define callbacks each time a javascript object's property is created/deleted/modified. This should allow me to do things this way:

var myObject = {};

function onSet(propertyName, propertyValue) {
    // Do whatever you want here
}

// Attach the 'onSet' function to 'myObject'
// so it will be called everytime we add it a property.

myObject.abc = 'xyz'; // should call "onSet('abc','xyz')"

I saw a Proxy object in the ECMAScript 6 documentation that could allow me to do that. The problem about it is that it is currently supported only by the latest versions of Firefox and by Edge.

I though I could do it using setters/getters, but it seems to be possible to define one only for properties (for example if x = {y:2}; I don't see how to define a setter for "x", but it is easy to do it for "x.y". Sadly that does not solve my problem).

Has anyone a solution regarding it or should I let my code as it is right now and wait for ECMAScript 6 to be supported everywhere?

Cocottier
  • 92
  • 1
  • 2
  • 10
  • In terms of waiting for the ES6 browser support, you can simply write your code now using proxies/getters&setters and transpile it with [Babel](http://babeljs.io/) to ES5. After browsers' support gets better, you simply remove the transpiler step and you'll already have the proper ES6 code ready right away. – jalooc Sep 21 '15 at 12:01
  • Possible duplicate of [Is there a way to monitor changes to an object?](http://stackoverflow.com/questions/6216553/is-there-a-way-to-monitor-changes-to-an-object) – Paul Sweatte Feb 11 '16 at 22:01

0 Answers0