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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With