Last Updated: January 11, 2017
·
2.004K
· fiveisprime

Observable objects in JavaScript

More here: http://eventargs.com/2012/11/30/lookout-js-and-observable-javascript-objects/

var watch = function(obj, prop, callback) {
  var oldValue = obj[prop]
    , newValue = oldValue
    , getter = function() { return newValue; }
    , setter = function(value) {
        oldValue = newValue;
        newValue = value;
        callback.call(obj, prop, oldValue, newValue);
      };

  // Attempt to delete the property. If this fails, the configurable
  // flag is set to false which means that any changes to the property
  // will throw a TypeError.
  if (delete obj[prop]) {
    if (Object.defineProperty) {
      // ECMAScript 5 standard.
      Object.defineProperty(obj, prop, {
        get: getter,
        set: setter
      });
    } else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
      // Older browsers.
      Object.prototype.__defineGetter__(obj, prop, getter);
      Object.prototype.__defineSetter__(obj, prop, setter);
    }
  }

  return this;
};