Skip to content

Instantly share code, notes, and snippets.

@Unitech
Forked from melanke/README.md
Created July 20, 2012 11:41
Show Gist options
  • Select an option

  • Save Unitech/3150291 to your computer and use it in GitHub Desktop.

Select an option

Save Unitech/3150291 to your computer and use it in GitHub Desktop.
watch the changes of some object or attribute
/**
* DEVELOPED BY
* GIL LOPES BUENO
* [email protected]
*
* USAGE:
*
* object.watch(function(){
* alert("some attribute of object has been changed");
* });
*
* object.watch([
* "attr1", "attr2"
* ],
* function(){
* alert("attribute attr1 or attr2 of object has been changed");
* });
*
* object.watch("attr1", function(){
* alert("attribute attr1 of object has been changed");
* });
*
* object.attr1 = "different value"; //will trigger all 3 functions declared before
* WORKS WITH ARRAYS TOO!
* object.attr1.push("new item"); //will trigger all 3 functions declared before
*/
Object.prototype.watch = function(){
if(arguments.length==1)
this.watchAll.apply( this, arguments );
else if(Array.isArray(arguments[0]))
this.watchMany.apply( this, arguments );
else
this.watchOne.apply( this, arguments );
}
Object.prototype.watchAll = function(watcher){
var props = [];
for(var prop in this){
if(!isFunction(this[prop]) && prop != "watchers" && prop != "__proto__")
props.push(prop);
}
this.watchMany(props, watcher);
};
Object.prototype.watchMany = function(props, watcher){
for(var prop in props){
this.watchOne(props[prop], watcher);
}
};
Object.prototype.watchOne = function(prop, watcher) {
var obj = this;
var val = obj[prop];
if(typeof(obj[prop])=="object")
obj[prop].watchAll(watcher);
if(!obj.watchers){
obj.watchers = {};
}
if(!obj.watchers[prop])
obj.watchers[prop] = [];
obj.watchers[prop].push(watcher);
var getter = function() {
return val;
};
var setter = function (newval) {
var oldval = val;
val = newval;
if(oldval != newval){
for(var wr in obj.watchers[prop]){
if(isInt(wr))
obj.watchers[prop][wr]();
}
}
};
if(Object.defineProperty) { // ECMAScript 5
Object.defineProperty(obj, prop, {
get: getter,
set: setter,
enumerable: false,
configurable: true
});
} else if(Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__){ // legacy
Object.prototype.__defineGetter__.call(obj, prop, getter);
Object.prototype.__defineSetter__.call(obj, prop, setter);
}
if(obj[prop]){
obj[prop].push=(function(){ //arrays
var original = Array.prototype.push;
return function() {
original.apply(this,arguments);
for(var wr in obj.watchers[prop]){
if(isInt(wr))
obj.watchers[prop][wr]();
}
};
})();
}
};
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) == '[object Function]';
}
function isInt(x) {
var y=parseInt(x);
if (isNaN(y)) return false;
return x==y && x.toString()==y.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment