Tha*_*sas 60 javascript variables wait
我想强制JavaScript程序在其执行的某些特定点等待,直到变量发生变化.有办法吗?我已经找到了一个名为"叙事JavaScript"的扩展,它强制程序等到事件发生.有没有办法创建一个新事件,例如一个"变量事件",其行为类似于onclick事件.
aul*_*ron 87
编辑2018:请查看Object getters and setters和Proxies.老答案如下:
一个快速简单的解决方案是这样的:
var something=999;
var something_cachedValue=something;
function doStuff() {
if(something===something_cachedValue) {//we want it to match
setTimeout(doStuff, 50);//wait 50 millisecnds then recheck
return;
}
something_cachedValue=something;
//real action
}
doStuff();
Run Code Online (Sandbox Code Playgroud)
Reb*_*oot 21
JavaScript解释器是单线程的,因此当代码在一些其他不改变变量的代码中等待时,变量永远不会改变.
在我看来,将变量包装在某种具有getter和setter函数的对象中是最好的解决方案.然后,您可以在调用对象的setter函数时在调用的对象中注册回调函数.然后,您可以在回调中使用getter函数来检索当前值:
function Wrapper(callback) {
var value;
this.set = function(v) {
value = v;
callback(this);
}
this.get = function() {
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
这可以很容易地使用:
<html>
<head>
<script type="text/javascript" src="wrapper.js"></script>
<script type="text/javascript">
function callback(wrapper) {
alert("Value is now: " + wrapper.get());
}
wrapper = new Wrapper(callback);
</script>
</head>
<body>
<input type="text" onchange="wrapper.set(this.value)"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我会推荐一个能够处理更改值的包装器.例如,您可以使用JavaScript函数,如下所示:
?function Variable(initVal, onChange)
{
this.val = initVal; //Value to be stored in this object
this.onChange = onChange; //OnChange handler
//This method returns stored value
this.GetValue = function()
{
return this.val;
}
//This method changes the value and calls the given handler
this.SetValue = function(value)
{
this.val = value;
this.onChange();
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以创建一个可以保存你想要监视的值的对象,以及一个在值发生变化时调用的函数.例如,如果您希望在值更改时收到警报,并且初始值为10,则可以编写如下代码:
var myVar = new Variable(10, function(){alert("Value changed!");});
Run Code Online (Sandbox Code Playgroud)
function(){alert("Value changed!");}调用时将调用处理程序(如果查看代码)SetValue().
你可以得到这样的价值:
alert(myVar.GetValue());
Run Code Online (Sandbox Code Playgroud)
您可以像这样设置值:
myVar.SetValue(12);
Run Code Online (Sandbox Code Playgroud)
紧接着,屏幕上会显示警报.看看它是如何工作的:http://jsfiddle.net/cDJsB/
| 归档时间: |
|
| 查看次数: |
98598 次 |
| 最近记录: |