我正在尝试创建一个所有实例都响应事件的类:
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");
}
}