Skip to content

Instantly share code, notes, and snippets.

@subtleGradient
Forked from appden/Object.watch.js
Created May 12, 2009 23:08
Show Gist options
  • Save subtleGradient/110782 to your computer and use it in GitHub Desktop.
Save subtleGradient/110782 to your computer and use it in GitHub Desktop.
// inspired by jQuery watch: http://plugins.jquery.com/files/jquery-watch.js.txt
(function(){
var watch = Object.prototype.watch,
unwatch = Object.prototype.unwatch,
watched = [],
timer;
Object.watch = function(obj, prop, fn){
if (watch) return watch.call(obj, prop, fn);
Object.unwatch(obj, prop); // one at a time pls
watched.push({
obj: obj,
prop: prop,
last: obj[prop],
fn: fn
});
if (!timer) timer = setInterval(function(){
for (var w, i = watched.length; w = watched[--i]; ){
if (w.obj[w.prop] !== w.last)
w.obj.last = w.obj[w.prop] = w.fn.call(w.obj, w.prop, w.last, w.obj[w.prop]);
}
}, 100);
};
Object.unwatch = function(obj, prop){
if (unwatch) return unwatch.call(obj, prop);
for (var w, i = watched.length; w = watched[--i]; ){
if (w.obj == obj && w.prop == prop){
watched.splice(i, 1);
break;
}
}
if (!watched.length) timer = clearInterval(timer);
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment