如何不断检查变量的值。例如:
if(variable == 'value'){
dosomething();
}
如果我不断地循环它,这将起作用,但是是否有一种有效的方法在变量设置为该值时立即触发它?
如何不断检查变量的值。例如:
if(variable == 'value'){
dosomething();
}
如果我不断地循环它,这将起作用,但是是否有一种有效的方法在变量设置为该值时立即触发它?
监视属性被赋值并在发生时运行函数。
Object.watch() for all browsers?介绍了在不支持本地化该特性的浏览器上执行Object.watch
的跨浏览器方法。
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;
obj.unwatch()
?如果其它代码已经在监听此属性,这会覆盖先前的监听吗?看起来更好的解决方案可能是类似于 obj.addListener('change', prop, listener);
这样的形式。 - user1944491使用 setInterval:
var key = ''
setInterval(function(){
if(key == 'value'){
dosomething();
}
}, 1000);
正如@Pekka所评论的,您可以定时轮询变量。如果所有更改变量的代码都是您自己的,则更好的解决方案是不仅直接设置变量,而是让所有设置器调用一个函数。该函数可以设置变量并执行您需要的任何其他处理。
function setValue(value) {
myVariable = value;
notifyWatchers();
}
如果您封装变量,使得该值只能通过调用函数进行设置,那么这将给您检查该值的机会。
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");
我曾经遇到过类似的问题,但是通过使用之前已经用过的定时函数,我成功地解决了它。即使您没有定时函数,也很容易创建;
var rand = 0
setInterval(function senseConst () {if (rand = 0) {rand = x}, 10);
//x could be equal to the variables value that you want to check
var widthSensorOutput = 0
setInterval(function senseConst () {if (widthSensorOutput = 0) {widthSensorOutput = document.getElementById('widthSensor').clientWidth}, 10);
//'widthSensor' is a div with the width equal to 100%
我不确定这是否是解决您问题的最佳方法,但对我有效。明确一下,这是Chandu提供的相同基本代码,只是我添加了您在进入函数后应该执行的操作,这已经非常明显了。我没有理解Chandu的帖子,也没有意识到他们使用了相同的根代码。