Listening for variable changes in JavaScript

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

    Easiest way I have found, starting from this answer:

    // variable holding your data
    const state = {
      count: null,
      update() {
        console.log(`this gets called and your value is ${this.pageNumber}`);
      },
      get pageNumber() {
        return this.count;
      },
      set pageNumber(pageNumber) {
        this.count = pageNumber;
        // here you call the code you need
        this.update(this.count);
      }
    };
    

    And then:

    state.pageNumber = 0;
    // watch the console
    
    state.pageNumber = 15;
    // watch the console
    

提交回复
热议问题