Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make an event listener that detects if a boolean variable becomes true?

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?

like image 649
trusktr Avatar asked Jul 21 '11 23:07

trusktr


1 Answers

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.
like image 160
gilly3 Avatar answered Sep 19 '22 20:09

gilly3