Advertisement
Guest User

Untitled

a guest
May 25th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. /**
  2. * Standalone function used to continuously watch the property of an object for changes.
  3. *
  4. * The function is as optimized as possible to reduce needless timeout and interval callbacks, but this should still be
  5. * used sparingly and only when events are not possible.
  6. *
  7. * Usage:
  8. * var item = watch(someObject, "propertyName", function(oldValue, newValue, cancel) {
  9. * // Handle the change here.
  10. * // Optionally cancel watching.
  11. * cancel();
  12. * });
  13. *
  14. * // You can also cancel with the return value.
  15. * item.cancel();
  16. */
  17. window.watch = (function() {
  18. var watchList = [], timer = null, timerResolution = 500;
  19.  
  20. function WatchItem(object, property, callback) {
  21. this.object = object;
  22. this.property = property;
  23. this.callback = callback;
  24. this.active = true;
  25. this.oldValue = object[property];
  26. }
  27.  
  28. WatchItem.prototype.cancel = function() {
  29. this.active = false;
  30.  
  31. var index = watchList.indexOf(this);
  32. if (index >= 0) {
  33. watchList.splice(index, 1);
  34. }
  35.  
  36. if (watchList.length === 0) {
  37. clearInterval(timer);
  38. timer = null;
  39. }
  40. };
  41.  
  42. function sentinel() {
  43. for (var i = 0; i < watchList.length; ++i) {
  44. var item = watchList[i];
  45. var newValue = item.object[item.property];
  46.  
  47. if (newValue !== item.oldValue) {
  48. item.callback(item.oldValue, newValue, item.cancel);
  49. }
  50.  
  51. if (!item.active) {
  52. --i;
  53. }
  54.  
  55. item.oldValue = newValue;
  56. }
  57. }
  58.  
  59. return function(object, property, callback) {
  60. var item = new WatchItem(object, property, callback);
  61. watchList.push(item);
  62.  
  63. if (timer === null) {
  64. timer = setInterval(sentinel, timerResolution);
  65. }
  66.  
  67. return item;
  68. };
  69. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement