Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object has been modified

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().

like image 923
Gabriel Llamas Avatar asked Jan 06 '13 00:01

Gabriel Llamas


1 Answers

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.

like image 163
ThiefMaster Avatar answered Sep 29 '22 01:09

ThiefMaster