object-watch.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // object.watch
  11. if (!Object.prototype.watch) {
  12. Object.defineProperty(Object.prototype, "watch", {
  13. enumerable: false
  14. , configurable: true
  15. , writable: false
  16. , value: function (prop, writeHandler, readHandler) {
  17. var
  18. oldval = this[prop]
  19. , newval = oldval
  20. , getter = function () {
  21. if(readHandler != undefined)
  22. readHandler.call(this, prop);
  23. return newval;
  24. }
  25. , setter = function (val) {
  26. oldval = newval;
  27. return newval = writeHandler.call(this, prop, oldval, val);
  28. }
  29. ;
  30. if (delete this[prop]) { // can't watch constants
  31. Object.defineProperty(this, prop, {
  32. get: getter
  33. , set: setter
  34. , enumerable: true
  35. , configurable: true
  36. });
  37. }
  38. }
  39. });
  40. }
  41. // object.unwatch
  42. if (!Object.prototype.unwatch) {
  43. Object.defineProperty(Object.prototype, "unwatch", {
  44. enumerable: false
  45. , configurable: true
  46. , writable: false
  47. , value: function (prop) {
  48. var val = this[prop];
  49. delete this[prop]; // remove accessors
  50. this[prop] = val;
  51. }
  52. });
  53. }