例如,我有 var menu_ready = false;
。我有一个 ajax 函数,它在 ajax 完成后将 menu_ready
设置为 true:
//set up event listener here
$(...).load(..., function() {
...
menu_ready = true;
}
如何设置等待 menu_ready
为真的事件监听器?
最佳答案
您不能将事件监听器附加到 JavaScript 变量本身,但您可以伪造它。使用具有 get
、set
和 listen
方法的对象,而不是 bool 变量:
function Bool(initialValue) {
var bool = !!initialValue;
var listeners = [];
var returnVal = function(value) {
if (arguments.length) {
var oldValue = bool;
bool = !!value;
listeners.forEach(function (listener, i, list) {
listener.call(returnVal, { oldValue: oldValue, newValue: bool });
});
}
return bool
};
returnVal.addListener = function(fn) {
if (typeof fn == "function") {
listeners.push(fn);
}
else {
throw "Not a function!";
}
};
return returnVal;
}
你会像这样使用它:
var menu_ready = Bool(false);
if (menu_ready()) {
// this code won't get executed, because menu_ready() will currently return false;
}
menu_ready.addListener(function (e) {
if (e.oldValue != e.newValue) {
// value changed!
}
});
menu_ready(true); // listeners are called.
关于javascript - 如何创建一个事件监听器来检测 bool 变量是否变为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6783876/