Listening for variable changes in JavaScript

后端 未结 22 2778
自闭症患者
自闭症患者 2020-11-21 06:57

Is it possible to have an event in JS that fires when the value of a certain variable changes? JQuery is accepted.

22条回答
  •  北海茫月
    2020-11-21 07:24

    It's not directly possible.

    However, this can be done using CustomEvent: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent

    The below method accepts an array of variable names as an input and adds event listener for each variable and triggers the event for any changes to the value of the variables.

    The Method uses polling to detect the change in the value. You can increase the value for timeout in milliseconds.

    function watchVariable(varsToWatch) {
        let timeout = 1000;
        let localCopyForVars = {};
        let pollForChange = function () {
            for (let varToWatch of varsToWatch) {
                if (localCopyForVars[varToWatch] !== window[varToWatch]) {
                    let event = new CustomEvent('onVar_' + varToWatch + 'Change', {
                        detail: {
                            name: varToWatch,
                            oldValue: localCopyForVars[varToWatch],
                            newValue: window[varToWatch]
                        }
                    });
                    document.dispatchEvent(event);
                    localCopyForVars[varToWatch] = window[varToWatch];
                }
            }
            setTimeout(pollForChange, timeout);
        };
        let respondToNewValue = function (varData) {
            console.log("The value of the variable " + varData.name + " has been Changed from " + varData.oldValue + " to " + varData.newValue + "!!!"); 
        }
        for (let varToWatch of varsToWatch) {
            localCopyForVars[varToWatch] = window[varToWatch];
            document.addEventListener('onVar_' + varToWatch + 'Change', function (e) {
                respondToNewValue(e.detail);
            });
        }
        setTimeout(pollForChange, timeout);
    }
    

    By calling the Method:

    watchVariables(['username', 'userid']);
    

    It will detect the changes to variables username and userid.

提交回复
热议问题