decor/Observable

Observable is an object working as a shim of ES7 Object.observe(). Observable has .set() method for automatic emission of change record, and static Observable.observe() method to observe for that, for example:

Similar to ES7 Object.observe(), change records are delivered in a batch at the end of the micro-task. In above example, you'll see that change to foo property and change to bar properties are notified in a single callback, in a format of array. The format of change records is compatible with ES7 Object.observe().

Under the hood, Observable.observe() directly uses ES7 Object.observe() if it's available natively in browser.

Synchronous delivery of change record

There are some cases you want to deliver change records immediately, instead of waiting for the end of micro-task. For that purpose, you can use Observable.deliverChangeRecord() that synchronously delivers change records that are queued for callback. Here's an example:

Manual emission of change record

Similar to Object.observe(), .set() won't automatically emit a change record if:

In such conditions, you can manually emit a change record (and queue it for delivery) by Observable.getNotifier(observable).notify(changeRecord) method, which is what .set() calls under the hood. Here's an example:

Synthetic change record

If you make a higher-level change to an object (as opposed to a simple property update/delete/add), such as array splice, having such higher-level change represented directly in a change record will be useful. You can do that by Observable.getNotifier(observable).performChange(type, callback) method. The first argument (type) is the change type you define for your higher-level change. The second argument is a function where you can make a series of changes that your higher-level change represents, and then return your higher-level change.

You can observe your higher-level change by adding the change type of your higher-level change to the third argument of Observable.observe(). Otherwise, raw changes to Observable (update, etc.) will be observed.

Here's an example, where Point#move() method moves the point with the given distance and direction (angle). The code to update x and y with the result is in performChange() callback so that the updates are represented by a change record with move type, with the distance and direction (angle):

Utility functions

Observable has two static utility funcitons: