var beingWatched = {};
function whatHappened(change) {
console.log(change.name + " was " + change.type + " and is now " + change.object[change.name]);
}
function somethingChanged(changes) {
changes.forEach(whatHappened);
}
Object.observe(beingWatched, somethingChanged);
beingWatched.a = "foo"; // new
beingWatched.a = "bar"; // updated
beingWatched.a = "bar"; // no change
beingWatched.b = "amazing"; // new
Object.observe()
lets you add a listener to any JavaScript object that gets called whenever that object, or its properties, change.
As mentioned before, Object.observe()
is coming in ECMAScript 6 (and is already available in Chrome Canary)
Object.observe() Demo →
Respond to change with Object.observe() →