2017-03-17 9 views
0

私はNode.jsでこのコードから生成されたイベントをキャプチャできない理由から頭を悩ましてきました。私の腸の感覚は、範囲外ですが、私はそれが何であるか把握できません。 console.logのコード行はindex.jsに決して実行されません。私のイベントは放出されていないのですか?Node.jsの拡張EventEmitterクラスからイベントを取得できないのはなぜですか?

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

スティックにいくつかのログを。 EventEmitterから継承する必要があります。 – Adam

+0

'.emit( 'nowPlaying'、{})'を呼び出しています – magreenberg

+0

私はplay関数のいくつかのロギングを持っています。emit呼び出しの後にエラーなしで出てきます。それはイベントがキャプチャされていないナットを運転しています。 –

答えて

1

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'); 
    } 
} 

const player = new rocketPlayer(); 

player.on('nowPlaying', title => { 
    console.log('caught nowPlaying event'); 
}); // <= fixed missing bracket 

//define a connection 
player.update('connection'); 

は注:私は単なる文字列

+0

私のオリジナルの投稿には、Typosがあります。あなたのコードは、私が必要とする別のファイルとmodules.exportメソッドを実装していません。 –

+0

あなたが投稿したように動作するはずです。私はテスト目的のために1つのファイルに入れます –

+0

私はそれがうまくいくはずですが、それは実現しません。 –

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); 

結果:あなた `update`と` play`メソッドの内部

PS D:\Code\data> node -v 
v7.4.0 
PS D:\Code\data> node ./index 
caught nowPlaying event Boooboo! 
+0

私はコードに戻ってIDEのメモリにバッファリングされたファイルを編集していたことに気づきました。プロジェクトファイルの名前を変更した後、私が作ったすべての編集は私のメインループでは参照されていませんでした。私はそれを今働いている、あなたの助けに感謝します。 –

関連する問題