问题
I'm trying to create a class for which all instances respond to an event:
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);
The recordClip function never seems to be called. Is this possible?
I also tried running this.recordClip
instead of recordClip
.
回答1:
Move it inside the constructor.
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");
}
}
来源:https://stackoverflow.com/questions/45601647/node-es6-class-event-emitter-function