gdfgdfg
gdfgdfg

Reputation: 3566

Emit and on - NodeJS in separate emodule inside a function

I have simple module - logger.js:

var EventEmitter = require('events');
var emitter = new EventEmitter();

const log = (message) => {
   emitter.emit('logging');
    console.log('here')
}

module.exports.log= log;

which I am importing in another file:

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('logging', () => {
    console.log('Logging:')
});

const logger = require('./logger');
logger.log(90);

, I see 90 - the message, but I don't see console.log('Logging:'), why is that ?

It works, if I put all in one file, without wrapping emit in function.

Upvotes: 1

Views: 39

Answers (1)

Tien Duong
Tien Duong

Reputation: 2595

Every EventEmitter object you create is a new instance so events fired from the first one won't be triggered in the second. You need to use the same EventEmitter object.

Upvotes: 2

Related Questions