当变量改变时发出事件

Emit an event when a variable changes

我想在变量改变发出一个事件,但它不起作用。

模块如下:

const EventEmitter = require("events");

const watcher = new EventEmitter();

let variable = 0;
let previous = 0;

function reassign(value) {
  variable = value;
}
module.exports = watcher;
module.exports.reassign = reassign;
while (true) {
    if (variable !== previous) {
        watcher.emit("change", previous, variable);
        previous = variable;
    } else
        console.log(variable); // output: 0
}

这是主要文件:

const watcher = require("./watcher.js");
watcher.on("change", (prev, variable) => {
  console.log(prev, variable);
});
watcher.reassign(10);

问题是 reassign() 函数不修改变量。有什么建议吗?

一个简单的解决方法是更改​​ module.exports。不要将整个导出声明为观察者 class,而是将两者都放在一个对象中并分别声明它们。

示例:

const EventEmitter = require("events");
const watcher = new EventEmitter();

let variable = 0;

/**
  * Reassign the variable
  * @param value The new value
  */
function reassign(value) {
    watcher.emit("change", variable, value);
    variable = value;
}

module.exports = { watcher, reassign };
const functions = require("./watcher.js");
const watcher = functions.watcher;
watcher.addListener("change", (prev, variable) => {
    console.log(`Old value: ${prev}, New value: ${variable}`);
});
functions.reassign(10);