简体   繁体   English

Node.js EventEmitter无法立即发射

[英]Node.js EventEmitter not working on immediate emit

The following problem: 出现以下问题:

I hava a class save.js that inherits event from EventEmitter. 我有一个类save.js,它从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. 因此,奇怪的行为是:永远不会发出console.log(self)之后的第一个发出事件。 but logging self shows that this class has already inherited the EventEmitter features. 但是记录自我显示该类已经继承了EventEmitter功能。 All Other events emitting correctly. 所有其他事件均正确发出。 Any hints? 有什么提示吗?

The emit method of EventEmitter does a synchronous call of all the currently registered handlers. EventEmitteremit方法对所有当前注册的处理程序进行同步调用。

The emit that is right after the console.log is called while the listener has not yet been registered. 在尚未注册侦听器时调用console.log之后的emit 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 如果你真的想在构造函数中发出一个事件像你这样在这里,你应该让这个emit总是与异步

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. 或者您可以使用一个不活动的构造函数,以便在新构造的对象上配置和获取引用,然后使用一个.setup.init方法启动该对象的事件活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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