我正在尝试在 javascript 中创建一个对象观察者。
这是据我所知:
//object to observe an object
observe : {
parent : this, //keep context of parent
references : {}, //keep track of setted references
originals : {}, // also for the originals
callStack : 0, // trying to prevent the callstack
// set an object to observe..
setObject : function ( name, object ){
this.references[name] = object;
//app.utils.extendObject is a working object extending function.
this.originals[name] = app.utils.extendObject( new Object , object );
//start watching the object
this.watchObject( name );
},
watchObject : function ( referenceName ){
this.callStack++;
//walk through reference
for( prop in this.references[referenceName] ){
// if the reference differs from the original...
if( this.references[referenceName][prop] !== this.originals[referenceName][prop] ){
//... log the differance
console.log( referenceName + " with property " + prop + " has changed." );
}
}
// set variable with call to this function
var func = eval( "app.utils.observe.watchObject(" + referenceName + ")" );
//read somewhere this could do the trick
if( callStack == 1000 ){
setTimeout( func , 100 );
}
func();
}
}
问题是调用堆栈错误,有没有更好的方法来观察这个?当然,我目前可以在 Chrome 中使用 Object.observe,但我想要一个跨浏览器的解决方案。
任何帮助表示赞赏!