0

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.

hindmost
  • 7,125
  • 3
  • 27
  • 39
Maris
  • 4,608
  • 6
  • 39
  • 68

1 Answers1

1

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
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • So you suggest to use `defineProperty` instead of native way of properties addition/modification/deletion? – hindmost Sep 01 '15 at 09:22
  • This is a possibility. It is a standard way to change the default behaviour of setting values on a property. – Davide Lorenzo MARINO Sep 01 '15 at 09:26
  • Very interesting approach! Thank you. – Maris Sep 01 '15 at 09:29
  • I used it playing for designing a two way data binding similar to angularJS. It works with 100 lines of code :-) – Davide Lorenzo MARINO Sep 01 '15 at 09:31
  • @DavideLorenzoMARINO That is exactly what I trying to achieve. :) – Maris Sep 01 '15 at 09:33
  • This is fine if you have to watch value changes *only* (no addition/deletion/etc) on a known set of properties, and you don't care about accessor performances or changing the property descriptor. On the "plus" part, you'll get *synchronous* notifications. But this isn't anything like `Object.observe`: if you need something like that, there's the polyfill Andy mentioned in his comment, which is compatible down to ES3 browsers (disclaimer: I'm the author of that polyfill). – MaxArt Sep 03 '15 at 12:20