Object.observe()

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() →

Published by Bramus!

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.