Skip to content
Advertisement

How to subscribe to object changes?

I wonder how to subscribe to the changes of a JavaScript object e.g. like Redux does. I read through a lot of JS documentations but I couldn’t find a non-deprecated way to handle this problem (Object.protype.watch() as well as Object.observe() are deprecated). Moreover I read a few Stackoverflow questions regarding this topic but they are all at least 5 years old. To visualize my problem I’ll show an example.

This could be an object I want to watch for:

const store = {
    anArray = [
    'Hi',
    'my',
    'name',
    'is'
  ]
}

.. and this a function which changes the store object:

function addAName() {
    store.anArray.push('Bob')
}

My goal in this example is to trigger the following function every time the store object changes

function storeChanged() {
    console.log('The store object has changed!')
}

Thank you in advance!

Advertisement

Answer

Have you tried using Proxy from ECMA6? I think this is what you are looking for You only have to define a function as the set of the validator of the Proxy like this:

let validator = {
    set: function(target, key, value) {
        console.log(`The property ${key} has been updated with ${value}`);
        return true;
    }
};
let store = new Proxy({}, validator);
store.a = 'hello';
// console => The property a has been updated with hello
Advertisement