object-observer

Observable API

Observable API provides the whole life cycle of object observation functionality.

Additionally, this API defines the Change object, list of which being a parameter of an observer callback function.

object-observer provides Observable top level object as a named import: import { Observable } from 'object-observer.js'

Static methods

Observable.from(input[, options])

let person = {
        name: 'Aya',
        age: '1',
        address: {
            city: 'city',
            street: 'street'
        }
    },
    observablePerson;

observablePerson = Observable.from(person);

Observable.isObservable(input)

Observable.isObservable({});                            //  false
Observable.isObservable(observablePerson);              //  true
Observable.isObservable(observablePerson.address);      //  true

Observable.observe(observable, callback[, options])

function personUIObserver(changes) {
    changes.forEach(change => {
        console.log(change.type);
        console.log(change.path);
        console.log(change.value);
        console.log(change.oldValue);
    });
}
...
//  following the observablePerson example from above
Observable.observe(observablePerson, personUIObserver, options);    //  options is optional

const observableAddress = observablePerson.address;
Observable.observe(observableAddress, personUIObserver);            //  nested objects are observables too

observablePerson.address = {};                          			//  see below

Attention! Observation set on the nested objects, like address in the example above, ‘sticks’ to that object. So if one replaces the nested object of the observable graph (see the last line of code above), observer callbacks are NOT moved to the new object, they stick to the old one and continue to live there - think of detaching/replacing a sub-graph from the parent.

Observable.unobserve([callback[, callback]+])

Observable.unobserve(observablePerson, personUIObserver);
//  or
Observable.unobserve(observablePerson);

//  same applies to the nested
Observable.unobserve(observableAddress);

Observation options

If/When provided, options MUST be an object. Unknown properties are rejected — incorrect observation options throw, to fail fast.

Change instance properties