4

Is it possible to execute some code each time an object has changed ?

var a = {x: 12, y: 63};

a.watch(function () { console.log('The object has changed!'); });

a.x = 16;   // The object has changed!
a.y = 1;   // The object has changed!

It seems to be available on Firefox only: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch

How is it possible to achieve this in JavaScript / node.js? (if possible, without using a getter/setter method)

Basj
  • 29,668
  • 65
  • 241
  • 451
  • in pure javascript, you can set timeout method or time interval for periodically checking object value. – Murtaza Khursheed Hussain Dec 23 '14 at 10:34
  • 1
    You should not use watch but use observe but it's still ECMAScript7 proposal https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe currently you should be able to do like [this](http://stackoverflow.com/questions/24745424/how-to-detect-if-an-object-variable-has-been-changed) – Bhojendra Rauniyar Dec 23 '14 at 10:35
  • @Marcus no, it won't. – Alnitak Dec 23 '14 at 10:35
  • Yeah, good old `watch` was a Netscape extension that (as far as I know) was never implemented by any other vendor. I'm curious about Node. – Álvaro González Dec 23 '14 at 10:36
  • @MurtazaHussain yes but how to know if the globally has *globally* changed? Imagine the object contains lots of data, we cannot check if each of the property has changed? – Basj Dec 23 '14 at 10:36
  • @Alnitak: Yeah. Checked that. Thanks :) – Sayed Dec 23 '14 at 10:37
  • @Basj you an create a pipeline object to watch single object rather than looking into whole large object itself – Murtaza Khursheed Hussain Dec 23 '14 at 10:38
  • @Basj one of the "nice" things about JS is that being a single-threaded language, objects cannot be changed "below the radar" unless you change them in your code. In most circumstances therefore it's easier to find those mutation points and look there for changes. – Alnitak Dec 23 '14 at 10:39
  • 2
    Also see ECMAScript6 Proxy https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy it may do this, but it will hurt your fillings – micnic Dec 23 '14 at 10:39

1 Answers1

4

You can use Object Observe... it's experimental so proceed with caution...

var obj = {
    foo: 0,
    bar: 1
};

Object.observe(obj, function(changes) {
    console.log(changes);
});

obj.baz = 2;
micnic
  • 9,275
  • 5
  • 38
  • 52
Edward J Beckett
  • 4,701
  • 1
  • 38
  • 39