我一直在抨击为什么我无法捕获Node.js中此代码发出的事件。我的直觉是超出范围,但我无法弄清楚它是什么。 console.log
中的index.js
代码行永远不会被执行。我的活动没有被发出吗?
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)
答案 0 :(得分:1)
你有一些拼写错误:你在听众之后错过了一个支架。您也没有将构造函数参数正确地传递给超级构造函数。以下代码适用于我:
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');
注意:由于您没有定义歌曲,我只是将其转换为字符串
答案 1 :(得分:0)
我认为您发布的示例有一些问题;值得注意的是,所写的歌曲方法是抛出异常。
player.js:
"use strict";
let EventEmitter = require('events').EventEmitter;
class RocketPlayer extends EventEmitter {
constructor(options) {
super(options);
}
update(connection) {
//do some logic with playlists
this.play(connection);
}
play(song) {
// do some stuff
this.emit('nowPlaying', song.title);
}
}
module.exports = RocketPlayer;
index.js:
const RocketPlayer = require('./player.js');
const player = new RocketPlayer();
const connection = {title: "Boooboo!"};
player.on('nowPlaying', title => {
console.log('caught nowPlaying event', title);
});
//define a connection
player.update(connection);
结果:
PS D:\Code\data> node -v
v7.4.0
PS D:\Code\data> node ./index
caught nowPlaying event Boooboo!