I Heart Object.observe()

If you have used AngularJS, or EmberJS and any other front-end Javascript based framework, then you would be familiar with the concept of data binding. Essentially being able to watch a Javascript object for changes and then call a function when this takes place.

Currently without using a third party library which implements a non-native method for observing changes in a object like Angular or a polyfill, there is no cross-browser method for observing objects for changes which doesn’t involve some kind of hack at the expense of performance.

While Object.observe() is really only currently supported in Chrome, it is without-a-doubt the future of Javascript. It means that the need for a front-end framework is lessened, not for now, but eventually, it will. Sadly, Object.observe() is not scheduled to land until ES7.

A basic example:

var someObj = {};

Object.observe(someObj, function(changes) {
    changes.forEach(function(change) {
        console.log({
            propertyNameAffected: change.name,
            oldValue: change.oldValue,
            changeType: change.type,
            affectedObject: change.object
        });
    });
});

// This will trigger an event and output the following in the console
// {propertyNameAffected: "myVal", oldValue: undefined, changeType: "add", affectedObject: Object}
someObj.myval = 'Dwayne';

// Changing the value of a pre-existing property will output the following in the console
// {propertyNameAffected: "myVal", oldValue: "Dwayne", changeType: "update", affectedObject: Object}
someObj.myval = 'Dwayne Again';

// Deleting the property from the object will output the following in the console
// {propertyNameAffected: "myVal", oldValue: "Dwayne Again", changeType: "delete", affectedObject: Object}
delete someObj.myval;

One of the best polyfills out there for Object.observe() support in all browsers, through the use of either the native method or dirty-checking is Observe-js.

As you can see one of the most touted benefits of front-end frameworks is data-binding and eventually people will favour native Javascript over frameworks as tasks that once required polyfills/frameworks/libraries to do can be done in a few lines of native JS.

The future is bright, man.

Leave a Reply

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