I want to emit an event whenever variable changes but it doesn't work.
Here is the module:
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
}
Here is the main file:
const watcher = require("./watcher.js");
watcher.on("change", (prev, variable) => {
console.log(prev, variable);
});
watcher.reassign(10);
The issue is that the reassign() function doesn't modify the variable. Any suggestions?
A simple fix would be to change the module.exports. Instead of declaring the entire exports as the watcher class, put both inside an object and declare them seperately.
Example:
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);