gpt4 book ai didi

rxjs ofObjectChanges 已过时

转载 作者:行者123 更新时间:2023-12-04 19:46:21 24 4
gpt4 key购买 nike

ofObjectChanges 建立在 Object.observe() 这是过时的( https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/observe )我正在寻找一种替代方法来观察对象属性的变化。有人知道吗?

最佳答案

也许使用代理是一种选择,尽管需要替换原始对象

const { Subject } = require('rxjs');

// Take an object, and return a proxy with an 'observation$' stream
const toObservableObject = targetObject => {
const observation$ = new Subject();
return new Proxy(targetObject, {
set: (target, name, value) => {
const oldValue = target[name];
const newValue = value;
target[name] = value;
observation$.next({ name, oldValue, newValue });
},

get: (target, name) => name == 'observation$' ? observation$ : target[name]
});
}

const observableObject = toObservableObject({ });

observableObject.observation$
.filter(modification => modification.name == 'something')
.subscribe(({ name, oldValue, newValue }) => console.log(`${name} changed from ${oldValue} to ${newValue}`));

observableObject.something = 1;
observableObject.something = 2;

输出
something changed from undefined to 1
something changed from 1 to 2

在兼容性表中查找 Proxy 当前节点版本已完全支持)
https://kangax.github.io/compat-table/es6/

和代理的文档在
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy

关于rxjs ofObjectChanges 已过时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com