我一直在绞尽脑汁思考为什么我无法捕获 Node.js 中这段代码发出的事件。我的直觉是有些东西超出了范围,但我不知道它是什么。 index.js
中的 console.log
代码行永远不会被执行。我的事件没有被发出吗?
player.js
const EventEmitter = require('events').EventEmitter;
class rocketPlayer extends EventEmitter {
constructor(options) {
super(options);
}
update(connection) {
//do some logic with playlists
this.play(connection);
}
play(connection) {
// do some stuff
this.emit('nowPlaying',song.title);
}
}
module.exports = rocketPlayer
index.js
const rocketPlayer = require('./player.js');
const player = new rocketPlayer();
player.on('nowPlaying', title => {
console.log('caught nowPlaying event');
});
//define a connection
player.update(connection)
最佳答案
你有一些拼写错误:你的听众后面缺少一个括号。您也没有正确地将构造函数参数传递给 super 构造函数。以下代码对我有用:
const EventEmitter = require('events').EventEmitter;
class rocketPlayer extends EventEmitter {
constructor(options) {
super(options);
}
update(connection) {
//do some logic with playlists
this.play(connection);
}
play(connection) {
// do some stuff
this.emit('nowPlaying', 'song.title');
}
}
const player = new rocketPlayer();
player.on('nowPlaying', title => {
console.log('caught nowPlaying event');
}); // <= fixed missing bracket
//define a connection
player.update('connection');
注意:由于您没有定义歌曲,我只是将其转换为字符串
关于javascript - 为什么我无法从 Node.js 中的扩展 EventEmitter 类捕获事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867658/