由于ObjectChanges建立在过时的Object.observe()上(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/observe)我正在寻找一个观察对象的替代方案财产变化.谁知道一个?
小智 4
也许使用代理是一种选择,尽管需要替换原始对象
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;
Run Code Online (Sandbox Code Playgroud)
输出
something changed from undefined to 1
something changed from 1 to 2
Run Code Online (Sandbox Code Playgroud)
在兼容性表中查找代理当前节点版本已完全支持) https://kangax.github.io/compat-table/es6/
代理文档位于 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy
| 归档时间: |
|
| 查看次数: |
1238 次 |
| 最近记录: |