Javascript: How do constantly monitor variables value

家住魔仙堡 提交于 2019-12-03 12:04:34
Mike Samuel

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.

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;

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

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

Use setInterval:

var key = ''
setInterval(function(){
  if(key == 'value'){
    dosomething();
  }
}, 1000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!