我正在尝试创建一个所有实例都响应事件的类:
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
。
最佳答案
将其移至构造函数内。
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");
}
}
关于javascript - Node ES6类事件发射器函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45601647/