Node.js EventEmitter not working on immediate emit

6.6k views Asked by At

The following problem:

I hava a class save.js that inherits event from EventEmitter.

it looks alike:

var util          = require('util');
var EventEmitter  = require('events').EventEmitter;

var save = function(pdf){
  var self = this;
  EventEmitter.call(self);

  console.log(self);

  self.emit('test', 'TEST!');

  function doSomeDatabaseStuff() {
    db.connect(function(err, connection) {
      if ( err ) self.emit('error', err);
      else {
        self.emit('test', 'TEST!');
      }
    });
}

util.inherits(save, EventEmitter);
module.exports = save;

I initiate it:

var saving = new save(pdf);

saving.on('sim', function(result){
  console.log(result);
});

So the strange behavior is: The first emit event right after console.log(self) is never emitted. but logging self shows that this class has already inherited the EventEmitter features. All Other events emitting correctly. Any hints?

1

There are 1 answers

0
Jerome WAGNER On BEST ANSWER

The emit method of EventEmitter does a synchronous call of all the currently registered handlers.

The emit that is right after the console.log is called while the listener has not yet been registered. This explains why this listener is not called.

If you really want to emit an event in the constructor like you do here, you should probably make this emit always async with

setImmediate(function() {
   self.emit('test', 'TEST!');
});

or you could have an inactive constructor in order to configure and grab a reference on the newly constructed object and then have a .setup or .init method that starts the event activity of the object.