I have an object, for example:
var o = {
a: 1
};
The user does:
o.a = 2;
How can I know if the o
object has been modified? I cannot touch the o
object so I cannot use Object.defineProperties()
.
Since you are in the node.js environment and thus don't have to care about crappy old JavaScript engines (i.e. old browsers) you can use Object.defineProperty()
to define properties with accessor functions. This allows you to execute a custom function whenever a certain property is read/written - so you can simply log the write and e.g. store it in a separate property.
var o = {};
Object.defineProperty(o, 'a', {
get: function() {
return this.__a;
},
set: function(value) {
this.__a = value;
this.__a_changed = true;
}
});
o.__a = 1;
Whenever a value is assigned to o.a
the __a_changed
property will be set. Of course it would be even cleaner to execute whatever you want to do on change right in the set
function - but it obviously depends on your code if you can do so in a useful way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With