3
我想在javascript中創建對象觀察者。試圖觀察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,但我想要一個交叉瀏覽器解決方案。
任何幫助表示讚賞!
嘿感謝您的快速反應! 這個綁定函數是做什麼的? 也像回調&&回調線的一些解釋。 我看到它的作品,這是偉大的! – HerrWalter
大致'綁定'是沒有必要的,我更新了代碼。 – dfsq
那麼你的編輯是有道理的! – HerrWalter