Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs ofObjectChanges obsolete

Tags:

rxjs

As ofObjectChanges is built on Object.observe() which is obsolete (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/observe) I'm looking for an alternative for watching object property changes. Anyone know of one?

like image 661
Brad Woods Avatar asked Mar 15 '16 01:03

Brad Woods


1 Answers

Perhaps using a Proxy is an option, though it's needed to replace the original object

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;

The output

something changed from undefined to 1
something changed from 1 to 2

Look for Proxy in the compatibility table current node versions has full support) https://kangax.github.io/compat-table/es6/

And documentation of the Proxy at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy

like image 59
Tal Avatar answered Oct 03 '22 03:10

Tal