2011-01-08 39 views
7

如何經常檢查變量值。例如:Javascript:如何不斷監視變量值

if(variable == 'value'){ 
    dosomething(); 
} 

如果我不斷地循環,或某事,這會的工作,但有一旦變量被設置爲該值從而觸發的有效途徑?

+1

具有定時功能。我認爲沒有其他辦法 – 2011-01-08 01:50:49

+0

有一些具體的實現方式。你有目標瀏覽器,還是儘可能多? – Hemlock 2011-01-08 01:54:38

+0

我正在創建一個移動應用程序,所以我擁有所有最新的Javascript技術和最佳實踐,因爲JS已轉換爲Objective C.我沒有設置函數的值,它是從第三方動態獲取的用戶點擊一個按鈕。我正在等待這個價值從默認變爲其他任何東西。 – Connor 2011-01-08 02:05:10

回答

3

使用的setInterval:

var key = '' 
setInterval(function(){ 
    if(key == 'value'){ 
    dosomething(); 
    } 
}, 1000); 
4

由於@Pekka評論,你可以有一個計時器不斷查詢變量。一個更好的解決方案,如果它是你改變變量的所有代碼,不是直接設置變量,而是讓所有setter調用一個函數。該函數然後可以設置變量並執行所需的任何其他處理。

function setValue(value) { 
    myVariable = value; 
    notifyWatchers(); 
} 
4

如果封裝變量以便只能通過調用函數來設置該值,則可以檢查該值。

function ValueWatcher(value) { 
    this.onBeforeSet = function(){} 
    this.onAfterSet = function(){} 

    this.setValue = function(newVal) { 
     this.onBeforeSet(value, newVal) 
     value = newVal; 
     this.onAfterSet(newVal) 
    } 
    this.getValue = function() { 
     return value; 
    } 
} 

var name = new ValueWatcher("chris"); 

wacthedName.onBeforeChange = function(currentVal, newVal) { 
    alert("about to change from" + currentVal + " to " + newVal); 
} 

name.setValue("Connor"); 
6
Object.defineProperty(Object.prototype, 'watch', { 
    value: function(prop, handler){ 
     var setter = function(val){ 
      return val = handler.call(this, val); 
     }; 
     Object.defineProperty(this, prop, { 
      set: setter 
     }); 
    } 
}); 

如何使用:

var obj = {}; 

obj.watch('prop', function(value){ 
    console.log('wow!',value); 
}); 

obj.prop = 3;