Quiero emitir un evento cada vez que cambia la variable pero no funciona.
Aquí está el módulo:
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 }Aquí está el archivo principal:
const watcher = require("./watcher.js"); watcher.on("change", (prev, variable) => { console.log(prev, variable); }); watcher.reassign(10);El problema es que la función reasign() no modifica la variable. ¿Alguna sugerencia?
Una solución simple sería cambiar module.exports . En lugar de declarar todas las exportaciones como la clase de observador, coloque ambas dentro de un objeto y declárelas por separado.
Ejemplo:
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);