object.watch

Observe changes on object properties.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/5314/20683/objectwatch.js

  1. /*
  2. * object.watch polyfill
  3. *
  4. * 2012-04-03
  5. *
  6. * By Eli Grey, http://eligrey.com
  7. * Public Domain.
  8. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  9. *
  10. */
  11.  
  12. // object.watch
  13. if (!Object.prototype.watch) {
  14. Object.defineProperty(Object.prototype, "watch", {
  15. enumerable: false,
  16. configurable: true,
  17. writable: false,
  18. value: function(prop, handler) {
  19. var oldval = this[prop],
  20. newval = oldval,
  21. getter = function() {
  22. return newval;
  23. },
  24. setter = function(val) {
  25. oldval = newval;
  26. return newval = handler.call(this, prop, oldval, val);
  27. };
  28. if (delete this[prop]) { // can't watch constants
  29. Object.defineProperty(this, prop, {
  30. get: getter,
  31. set: setter,
  32. enumerable: true,
  33. configurable: true
  34. });
  35. }
  36. }
  37. });
  38. }
  39.  
  40. // object.unwatch
  41. if (!Object.prototype.unwatch) {
  42. Object.defineProperty(Object.prototype, "unwatch", {
  43. enumerable: false,
  44. configurable: true,
  45. writable: false,
  46. value: function(prop) {
  47. var val = this[prop];
  48. delete this[prop]; // remove accessors
  49. this[prop] = val;
  50. }
  51. });
  52. }