Observable Object

import { Disposable } from ‘aurelia-framework’; // or ‘aurelia-binding’

export class MyClass {

@bindable obj: object;

subscriptions: Disposable[];

objChanged(newObj) {
if (this.subscriptions) {
this.subscriptions.forEach(subscription => subscription.dispose());
this.subscriptions = undefined;
}
if (newObj) {
this.subscriptions = this.observeObj(newObj);
}
}

/**

  • Return a list of disposables, each mapped to a subscription of corresponding property on a given obj
    */
    observeObj(obj: object): Disposable[] {
    return Object.keys(obj).forEach(propertyName => {
    this.be.propertyObserver(obj, propertyName).subscribe((newValue, oldValue) => {
    // do something with new value
    });
    });
    }
    }

Hi all,
this is a code to observable an object. This work very well.
I took the code from here : set object that has observed properties breaks the observing system · Issue #935 · aurelia/framework · GitHub .

But I have a question:
How can I know whick property changed, so I can replace with the new value. For the moment I have only the old and new vales but I can’t do nothing with only them.

Thanks for the help!
Andrea

well, when you enumerate all the properties - you have the property name in hand, so you can you is in the lambda expression.

return Object.keys(obj).forEach(propertyName => {
    this.be.propertyObserver(obj, propertyName).subscribe((newValue, oldValue) => {
        // do something with new value
        console.log(propertyName);
    });
});
1 Like