Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Emit an event when a variable changes

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!