Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda