2017-08-09 61 views
0

我試圖創建一個類的所有實例對事件作出響應:節點ES6類事件發射器功能?

const events = require("events"); 
const eventEmitter = new events.EventEmitter(); 

class Camera { 
    constructor(ip) { 
     this.ip = ip;  
    } 

    eventEmitter.on("recordVideo", recordClip); 

    recordClip() { 
     console.log("running record video"); 
    } 
} 

// emit event once a minute 
setInterval(function(){ 
    eventEmitter.emit('recordVideo'); 
}, 1000*60); 

的recordClip功能似乎永遠不會被調用。這可能嗎?

我也試過運行this.recordClip而不是recordClip

+4

爲什麼你在類聲明中聲明而不在構造函數或其他方法中? – MinusFour

+0

「所有實例」在沒有實例化時也意味着「沒有實例」。 – Bergi

回答

1

將其移到構造函數中。

const events = require("events"); 
const eventEmitter = new events.EventEmitter(); 

class Camera { 
    constructor(ip) { 
     this.ip = ip; 
     eventEmitter.on("recordVideo", this.recordClip.bind(this)); 
    } 

    recordClip() { 
     console.log("running record video"); 
    } 
}