简体   繁体   English

观察现有对象上的对象属性更改

[英]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. 过去可以在任何对象上调用Object.observe() ,然后在修改属性时接收回调。 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声明为const ,因此无法使用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 state是通过引用传递给内部函数的,因此即使state被重新定义,该函数也将继续使用原始对象

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. 尽管可以使用setInterval不断地将state.attr与自身的state.attr版本进行比较来实现此state.attr ,但它无法捕获在setInterval调用之间发生的更改,并且始终会滞后。

Are there any lesser known methods that can achieve this? 有什么鲜为人知的方法可以实现这一目标吗?

Use Object.defineProperties resp. 请分别使用Object.defineProperties Object.defineProperty to create getters and setters on existing objects. Object.defineProperty在现有对象上创建获取器和设置器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM