Listening for variable changes in JavaScript

后端 未结 22 3293
自闭症患者
自闭症患者 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条回答
  •  萌比男神i
    2020-11-21 07:30

    I came here looking for same answer for node js. So here it is

    const events = require('events');
    const eventEmitter = new events.EventEmitter();
    
    // Createing state to watch and trigger on change
    let x = 10 // x is being watched for changes in do while loops below
    
    do {
        eventEmitter.emit('back to normal');
    }
    while (x !== 10);
    
    do {
        eventEmitter.emit('something changed');
    }
    while (x === 10);
    

    What I am doing is setting some event emitters when values are changed and using do while loops to detect it.

提交回复
热议问题