Xeos
Xeos

Reputation: 6497

Observe object property changes on existing object

It used to be possible to call Object.observe() on any object and then receive callbacks when properties were modified. However, it was deprecated and we were given Proxies and getters and setters as alternatives. But neither one allows attaching a listener to an existing object, references to which are already stored elsewhere. Taking this code as an example:

const state = {};

/* BEGIN Third party code */
(function runProcessing() {
    setInterval(globalState => {
        if (Math.random() > 0.5) {
            globalState.attr = !globalState.attr;
        }
    }, 1000, state);
})();
/* END Third party code */

// TODO: run some function every time state.attr is changed

There are two immediate problems:

While this can be achieved using setInterval that constantly compares the state.attr to previous version of itself, it would fail to catch changes that happen in between the setInterval invocations and it would always have lag.

Are there any lesser known methods that can achieve this?

Upvotes: 0

Views: 669

Answers (1)

connexo
connexo

Reputation: 56853

Use Object.defineProperties resp. Object.defineProperty to create getters and setters on existing objects.

Upvotes: 1

Related Questions