Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Standalone function used to continuously watch the property of an object for changes.
- *
- * The function is as optimized as possible to reduce needless timeout and interval callbacks, but this should still be
- * used sparingly and only when events are not possible.
- *
- * Usage:
- * var item = watch(someObject, "propertyName", function(oldValue, newValue, cancel) {
- * // Handle the change here.
- * // Optionally cancel watching.
- * cancel();
- * });
- *
- * // You can also cancel with the return value.
- * item.cancel();
- */
- window.watch = (function() {
- var watchList = [], timer = null, timerResolution = 500;
- function WatchItem(object, property, callback) {
- this.object = object;
- this.property = property;
- this.callback = callback;
- this.active = true;
- this.oldValue = object[property];
- }
- WatchItem.prototype.cancel = function() {
- this.active = false;
- var index = watchList.indexOf(this);
- if (index >= 0) {
- watchList.splice(index, 1);
- }
- if (watchList.length === 0) {
- clearInterval(timer);
- timer = null;
- }
- };
- function sentinel() {
- for (var i = 0; i < watchList.length; ++i) {
- var item = watchList[i];
- var newValue = item.object[item.property];
- if (newValue !== item.oldValue) {
- item.callback(item.oldValue, newValue, item.cancel);
- }
- if (!item.active) {
- --i;
- }
- item.oldValue = newValue;
- }
- }
- return function(object, property, callback) {
- var item = new WatchItem(object, property, callback);
- watchList.push(item);
- if (timer === null) {
- timer = setInterval(sentinel, timerResolution);
- }
- return item;
- };
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement