Javascript: How do constantly monitor variables value

末鹿安然 提交于 2020-01-01 04:36:09

问题


How do I constantly check a variables value. For example:

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

This would work if I constantly looped it or something, but is there an efficient way of triggering that as soon as the variable is set to that value?


回答1:


Object.watch:

Watches for a property to be assigned a value and runs a function when that occurs.

Object.watch() for all browsers? talks about cross-browser ways to do Object.watch on browsers that don't support it natively.




回答2:


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
        });
    }
});

How to use:

var obj = {};

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

obj.prop = 3;



回答3:


As @Pekka commented, you can have a timer constantly poll the variable. A better solution, if it's all your code that's changing the variable, is to not just set the variable directly, but rather have all setters call a function. The function could then set the variable and do any additional processing you need.

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



回答4:


If you encapsulate your variable so that the value can only be set by calling a function, it gives you the opportunity to check the value.

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");



回答5:


Use setInterval:

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


来源:https://stackoverflow.com/questions/4631896/javascript-how-do-constantly-monitor-variables-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!