2017-03-17 29 views
0

我一直在抨擊我的頭,因爲我無法捕獲在Node.js中從此代碼發出的事件。我的直覺感覺是有一些超出範圍的,但我無法弄清楚它是什麼。 index.js中的console.log行代碼永遠不會被執行。我的活動沒有被排出?爲什麼我無法從Node.js中的擴展EventEmitter類捕獲事件?

player.js

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

堅持你的'update'和'play'方法裏面的一些日誌。從EventEmitter繼承是按原樣完成的。 – Adam

+0

你在哪裏調用'.emit('nowPlaying',{})' – magreenberg

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

注:因爲你沒有定義的歌,我只是把它轉換成字符串

+0

在我原來的文章中的錯別字,你的代碼沒有實現單獨的文件和modules.export方法,我需要。 –

+0

應該像你發佈一樣工作。我把它放在一個文件中僅用於測試目的 –

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

結果:

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

我回到了代碼中,發現我一直在編輯一個文件,該文件在我的IDE中被緩存在內存中,並且在我重命名了一些項目文件後以某種方式在驅動器上恢復了它,所以我所做的每一個編輯都沒有在我的主循環中被引用。我現在正在工作,謝謝你的幫助。 –

相關問題