javascript 如何将更改事件处理程序附加到变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11729598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:09:31  来源:igfitidea点击:

How can I attach a change event handler to a variable?

javascriptjquery

提问by Travis J

Possible Duplicate:
Listening for variable changes in JavaScript or jQuery

可能的重复:
监听 JavaScript 或 jQuery 中的变量变化

How can I track if this variable has changed?

如何跟踪此变量是否已更改?

var ConditionalFlag = 0;

I tried this:

我试过这个:

var ConditionalFlag = 0;
$(ConditionalFlag).change(function () {
    alert("Changed");
});
ConditionalFlag++;

But to no avail. I have considered using a 25ms timer to check for change like this:

但无济于事。我曾考虑使用 25ms 计时器来检查这样的变化:

var ConditionalFlag = 0;
function CheckFlag() {
    if (ConditionalFlag > 0) {
        alert("Changed");
        clearInterval(check);
    }
}
var check = window.setInterval("CheckFlag()", 25);
ConditionalFlag++;

However, that seems like overkill. Is there a way to attach an event handler to this variable with jQuery or javascript?

然而,这似乎有点矫枉过正。有没有办法使用 jQuery 或 javascript 将事件处理程序附加到这个变量?

采纳答案by Rocket Hazmat

There's no "event" that gets triggered when a variable changes. JavaScript doesn't work that way.

当变量发生变化时,不会触发“事件”。JavaScript 不是这样工作的。

When does this variable get changed? Just add a call to a function after it does.

这个变量什么时候改变?只需在调用后添加对函数的调用。

回答by Travis J

If it's a global variable, you can use property accessors in supported environments...

如果它是全局变量,则可以在支持的环境中使用属性访问器...

window._conditional_flag = 0;
Object.defineProperty(window, "ConditionalFlag", {
    get: function() { return window._conditional_flag},
    set: function(v) { console.log("changed"); window._conditional_flag = v; }
});