Node ES6 class event emitter function?

微笑、不失礼 提交于 2019-12-12 06:38:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!