Last Updated: January 11, 2017
·
2.23K
· 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;
};

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside