Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Know when object value is modified

For any variable or property thereof, is there a way to know when its value is set?

For example, say I have:

let x = { 'a': 1, 'b': 2 };
// x.a's set operation is linked to a method
x.a = 3; // the method is automatically called

Is there a way I can call a function when a's value is changed? Lots of code would be changing this value; I don't want to add the method call all over the place.

I'm aware of Proxies, but to use them seems to require a separate variable. Meaning, x can't be a proxy of itself.

Preferably this technique would work with primitive and non-primitives.

like image 906
Karric Avatar asked Sep 27 '26 07:09

Karric


1 Answers

x can't be a proxy of itself

Sure it can. You can change the variable to point to a Proxy by simply doing

x = new Proxy(x, handler)

Primitive example:

const handler = {
  set: function(obj, prop, value) {
    console.log('setting prop: ', prop, ' to ', value)
    obj[prop] = value;
    return true;
  }
};

let x = { 'a': 1, 'b': 2 };

x = new Proxy(x, handler);

x.a = 3; // the method is automatically called
like image 114
charlietfl Avatar answered Sep 28 '26 22:09

charlietfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!