0

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 Proxy
  • state was passed by reference to an inner function, so even if state is redefined, the function will continue working with the original object

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?

2
  • 1
    Use Object.defineProperties resp. Object.defineProperty to create getters and setters on existing objects. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 19, 2019 at 19:06
  • @connexo, that's exactly what I was looking for. Commented Jun 19, 2019 at 19:09

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.