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