Reputation: 6497
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:
state
is declared a const
, so it can't be redefined using Proxystate
was passed by reference to an inner function, so even if state
is redefined, the function will continue working with the original objectWhile 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
Reputation: 56853
Use Object.defineProperties
resp. Object.defineProperty
to create getters and setters on existing objects.
Upvotes: 1