[英]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
。 不是將整個導出聲明為觀察者類,而是將它們都放在一個對象中並單獨聲明它們。
例子:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.