2011-05-10 85 views
6
// A simple Javascript Object/String 
var object = "hello"; 

// Imagine a button in the DOM, and if it's clicked the object value will change 
document.getElementById("button").onclick = function(){ 
    window.object = "hello world"; 
} 

// Now I would like to track and do something when the object is changed, ex: 
object.onreadystatechange = function(){ 
    alert(object); 
} 

注:這可能聽起來很蠢,因爲我能得到在按鈕上的onclick事件的變化,但是這不是我想要的,我要嚴格跟蹤對象的變化本身用於任何類型的用途,上面的代碼僅僅是一個例子。跟蹤對象是否改變

回答

5

那麼你可以把它的實際oject用get和set方法:

// A simple Javascript Object 
var object = new (function(){ 
    this.text = 'hello'; 

    this.setText = function(msg){ 
     this.text = msg 
     //on change event 
    } 
})(); 

// Imagine a button in the DOM, and if it's clicked the object value will change 
document.getElementById("button").onclick = function(){ 
    object.setText('New Text'); 
} 

這裏是一個演示小提琴:http://jsfiddle.net/maniator/BSYpz/

+1

ahum,不錯的把戲:) – Adam 2011-05-10 15:38:24

+0

:-D謝謝你:-) – Neal 2011-05-10 15:39:51

6

JavaScript不允許您在任意對象/變量上設置程序化觀察點/事件。

您可以使用封裝來從外部世界隱藏對象內部的各個值,只允許通過具有所需副作用的專用「setter」函數修改它們。

3

無論您想使用哪種框架,自動觸發屬性更改事件都沒有什麼神奇之處。在你的情況,你應該做的可能是使一個物體環繞這個數據,只有公開獲取併爲其設置方法:

var something = function() 
{ 
    var value = 10; 

    this.getValue = function() 
    { 
     return value; 
    } 

    this.setValue = function(newValue) 
    { 
     ValueChanging(value, newValue); 
     value = newValue; 
    } 

    var ValueChanging = function(old, new) 
    { 
     // Do Something 
    } 
}