0

Can somebody explain me why this following code don't work :

i have a EventManager class :

const events        = require('events')

class EventManager extends events.EventEmitter {
    constructor() { super() }
}

const instance = new EventManager()

module.exports = instance

i have a init.js file that require this EventManager and register some event like this :

const EventManager = require('./EventManager')
const processTask  = require('./processTask')

EventManager.on('startTask', (task) => {
    processTask(task)
})

EventManager.on('endTask', (task) => {
    //some code
})

const someTask = {}
EventManager.emit('startTask', someTask)

in my processTask function, i call the EventManager and emit endTask event :

// processTask.js
const EventManager  = require('../lib/EventManager')
module.exports = (task) => {

  // some code

  EventManager.emit('endTask')
}

but endTask is never emitted, why ?

Rav87
  • 57
  • 7
  • Never export single instances of local classes from modules. And why are you inheriting at all? – Bergi Jan 16 '17 at 13:48
  • 1
    What exactly is the `// some code`? Are you getting any exceptions? – Bergi Jan 16 '17 at 13:49
  • 1
    running your code and putting the EventManager.emit('endTask') within a setTimeout in the processTask file works for me. Id comment out all of the "some code" you have in there and see if it works then. if it does then it is probably not reaching the emit call. – poeticGeek Jan 19 '17 at 21:57
  • @Bergi, why it is not good to export single instances of local classes ? is it something to do with the module caching ? – Rav87 Jan 24 '17 at 15:25
  • No, it's just that for single instances it's pointless to create a class with all the inheritance overhead. If you want to export a singleton, make it an object literal (or, in your case, a `new EventEmitter` that is modified to your needs). – Bergi Jan 24 '17 at 15:31

1 Answers1

1

It was a problem in // some code. thx @Bergi and @poeticGeek.

Rav87
  • 57
  • 7