2013-03-28 115 views
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,但我想要一個交叉瀏覽器解決方案。

任何幫助表示讚賞!

回答

1

我修改了一下你的代碼,將callback函數加入watchObject方法。如果您想要聽取更改並執行某些操作,這很有用。

watchObject: function (referenceName, callback) { 
    for (prop in this.references[referenceName]) { 
     if (this.references[referenceName][prop] !== this.originals[referenceName][prop]) { 
      console.log(referenceName + " with property " + prop + " has changed."); 
      callback && callback.call(this.references[referenceName], this.originals[referenceName][prop], this.references[referenceName][prop]); 
      this.originals[referenceName][prop] = this.references[referenceName][prop]; 
     } 
    } 
} 

加上我放在setIntervalsetObject

var self = this; 
setInterval(function() { 
    self.watchObject(name, callback); 
}, 300); 

http://jsfiddle.net/59Fnt/1/

+0

嘿感謝您的快速反應! 這個綁定函數是做什麼的? 也像回調&&回調線的一些解釋。 我看到它的作品,這是偉大的! – HerrWalter

+0

大致'綁定'是沒有必要的,我更新了代碼。 – dfsq

+0

那麼你的編輯是有道理的! – HerrWalter