简体   繁体   中英

Node.js EventEmitter not working on immediate emit

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM