rxjs ofObjectChanges 已过时

rxjs ofObjectChanges obsolete

由于 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

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

以及 Proxy 的文档位于 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy