Search code examples
javascriptnode.jsecmascript-6eventemitteres6-class

Node ES6 class event emitter function?


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.


Solution

  • 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");
        }
    }