Node.js发射器如何工作?理解传递参数

时间:2017-04-30 08:48:28

标签: node.js events

我不明白如何使用function(msg)...调用myEmmiter.emit .emit('someEvent', ...)如何知道论据'the event was emitted'应该传递给function(msg)...? 有没有办法查看emit方法来源?

const events = require('events');
var myEmmiter = new events.EventEmitter();

myEmmiter.on('someEvent', function (msg) {
  console.log(msg);
});

myEmmiter.emit('someEvent', 'the event was emitted');

1 个答案:

答案 0 :(得分:2)

events模块的实现可在此处找到:https://github.com/nodejs/node/blob/master/lib/events.js

在摘要中,EventEmitter实例维护一个对象,其中键是事件名称(someEvent),值是每当生成该事件时应调用的函数数组:

this.registeredEvents = {
  someEvent : [ handler ]
};

要注册活动,请使用emitter.on()/emitter.addListener()

on(eventName, handler) {
  if (! Array.isArray(this.registeredEvents[eventName])) {
    this.registeredEvents[eventName] = [];
  }
  this.registeredEvents[eventName].push(handler);
}

当您调用emitter.emit()时,将使用参数:

调用每个处理程序
emit(eventName, message) {
  (this.registeredEvents[eventName] || []).forEach(handler => handler(message));
}