Listening for variable changes in JavaScript

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

    Yes, this is now completely possible!

    I know this is an old thread but now this effect is possible using accessors (getters and setters): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters

    You can define an object like this, in which aInternal represents the field a:

    x = {
      aInternal: 10,
      aListener: function(val) {},
      set a(val) {
        this.aInternal = val;
        this.aListener(val);
      },
      get a() {
        return this.aInternal;
      },
      registerListener: function(listener) {
        this.aListener = listener;
      }
    }
    

    Then you can register a listener using the following:

    x.registerListener(function(val) {
      alert("Someone changed the value of x.a to " + val);
    });
    

    So whenever anything changes the value of x.a, the listener function will be fired. Running the following line will bring the alert popup:

    x.a = 42;
    

    See an example here: https://jsfiddle.net/5o1wf1bn/1/

    You can also user an array of listeners instead of a single listener slot, but I wanted to give you the simplest possible example.

提交回复
热议问题