One of the most important ES6 features arriving is browsers is the Object.observe
API. Here's how MDN describes it, emphasis mine.
The
Object.observe()
method is used for asynchronously observing the changes to an object. It provides a stream of changes in the order in which they occur.
Consider the following code... what do you expect the output to be?
var obj = { foo: 'bar' };
function handleChange(records) {
console.log('!CHANGE!');
}
Object.observe(obj, handleChange);
console.log('BEGIN');
obj.foo = 'baz';
console.log('END');
If you guessed BEGIN, END, !CHANGE!
, congratulations you are the oracle of ES6 knowledge. If you guessed BEGIN, !CHANGE!, END
you obviously didn't see the asynchronously part of the description.
The interesting thing is ES6 provides a method for delivering the changes synchronously called Object.deliverChangeRecords
. This doesn't seem to be well documented yet, I only happened across the method in some Aurelia feature detection code.
The deliverChangeRecords
method takes one argument, a callback instance previously used in an Object.observe
call. If there are any changes in the queue for that callback, deliverChangeRecords
will flush them synchronously. Let's update the code snippet to output BEGIN, !CHANGE!, END
...
var obj = { foo: 'bar' };
function handleChange(records) {
console.log('!CHANGE!');
}
Object.observe(obj, handleChange);
console.log('BEGIN');
obj.foo = 'baz';
// Deliver the changes synchronously.
Object.deliverChangeRecords(handleChange);
console.log('END');
Here's a live example (use chrome):