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

前端 未结 7 2096
-上瘾入骨i
-上瘾入骨i 2020-12-31 19:52

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:

//se         


        
7条回答
  •  青春惊慌失措
    2020-12-31 20:36

    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.
    

提交回复
热议问题