Listening for variable changes in JavaScript

后端 未结 22 3299
自闭症患者
自闭症患者 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:26

    Recently found myself with the same issue. Wanted to listen for on change of a variable and do some stuff when the variable changed.

    Someone suggested a simple solution of setting the value using a setter.

    Declaring a simple object that keeps the value of my variable here:

    var variableObject = {
        value: false,
        set: function (value) {
            this.value = value;
            this.getOnChange();
        }
    }
    

    The object contains a set method via which I can change the value. But it also calls a getOnChange() method in there. Will define it now.

    variableObject.getOnChange = function() {
        if(this.value) {
            // do some stuff
        }
    }
    

    Now whenever I do variableObject.set(true), the getOnChange method fires, and if the value was set as desired (in my case: true), the if block also executes.

    This is the simplest way I found to do this stuff.

提交回复
热议问题