View on GitHub


ES6 Object.observe with nested object support

Download this project as a .zip file Download this project as a tar.gz file


Do you dream of observing a plain javascript object for changes and reacting to it later? Now you can.

Hiding being the --harmony flag of Node 0.11, the Object.observe gem resides.

Object.observe allows us to register a listener for any type of change to a given object.

// node --harmony

var o = { name: 'harmony' };
Object.observe(o, function (changes) {
}) = 'ES6!'
o.kind = 'observed';

// logs..
// [ { type: 'updated',
//     object: { name: 'ES6!', kind: 'observed' },
//     name: 'name',
//     oldValue: 'harmony' },
//   { type: 'new',
//     object: { name: 'ES6!', kind: 'observed' },
//     name: 'kind' } ]

You'll notice our callback received an array of all changes that occured. Cool. But what about nested objects? Do they get automatically observed as well?

// node --harmony

var o = { nested: { deeper: true }};
Object.observe(o, function (changes) {
o.nested.deeper = false
// crickets ..

Turns out they don't. That's what observed is for: watching objects for changes without having to care about whether or not they have nested objects and arrays.


observed returns an EventEmitter which you listen to for changes. There are four classes of events, mirroring Object.observe

var O = require('observed')
var object = { name: {} }
var ee = O(object)

ee.on('new', console.log) = 'observed'

// logs
// { path: 'name.last',
//   name: 'last',
//   type: 'new',
//   object: { last: 'observed' },
//   value: 'observed',
//   oldValue: undefined }

You'll notice we now receive more information compared to Object.observe

You may also listen for changes to specific paths:

var O = require('observed')
var object = { name: { last: 'Heckmann', first: 'aaron' }}
var ee = O(object)

ee.on('updated name.first', console.log) = 'Aaron'

// logs
// { path: 'name.first',
//   name: 'first',
//   type: 'updated',
//   object: { last: 'Heckmann', first: 'Aaron' },
//   value: 'Aaron',
//   oldValue: 'aaron' }

use cases

  1. passing object changes down to a browser in realtime using something like primus.
  2. fanning out object changes across multiple nodes using something like axon.
  3. buffering changes and pass them off to your database of choice in one save action.


  1. Object tracking: Using ES6 Object.observe we provide support for rich object tracking without manual getters/setters.
  2. Unobtrusive: Your object remains untouched and you may work with it as a plain js object.
  3. Events: Receive an EventEmitter back which emits the following events:


You must run node using the --harmony flag to use this module.

> node --harmony yourProgram.js


Run em with npm test