Search code examples
javascriptecmascript-5ecmascript-harmony

Object|Array.observe() implementation for ECMA 5


I found new useful experimental (in ECMA 7) method for Object and Array: observe. By the documentation you can subscribe for any changes in Object or Array. Unfortunately it is available only in Chrome 36 and Opera 23.

Do someone have idea how to implement that function for other browser (for browsers which supports ECMA 5)?

Thanks for any advance.


Solution

  • It is possible using Object.defineProperty

    Basically you redefine the set and get methods of the property you like to monitor with a code similar to the following:

    Object.defineProperty(obj, propertyName, { 
            configurable: true,
            enumerable: true,
            set: function(val) {
                notifyAll(val);   // This is a custom function to notify
                                  // the new value to all the listeners    
                value = val;      
            },
            get: function() {
                return value;
            }
        }); 
    

    For example

    var obj = {};
    Object.defineProperty(obj, 'name', { 
            configurable: true,
            enumerable: true,
            set: function(val) {
                console.log('Changed name to: ' + val);   
                value = val;      
            },
            get: function() {
                return value;
            }
        });
    
    
    obj.name = 'pippo'; // Logs Changed name to pippo
    obj.name = 'pluto'; // Logs changed name to pluto
    console.log(obj.name); // Logs pluto