我不明白如何使用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');
答案 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));
}