0

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.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225

1 Answers1

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");
    }
}
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247