For example, I have var menu_ready = false;
. I have an ajax function that sets menu_ready
to true when the ajax stuff is done:
//set up event listener here
$(...).load(..., function() {
...
menu_ready = true;
}
How do I set up an event listener that waits for menu_ready
to be true?
You can't attach event listeners to JavaScript variables per se, but you can fake it. Instead of a boolean var, use an object with get
, set
, and listen
methods:
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;
}
You'd use it like this:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With