Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda