节点ES6类事件发射器功能?

时间:2017-08-09 22:35:41

标签: javascript node.js ecmascript-6 eventemitter es6-class

我正在尝试创建一个所有实例都响应事件的类:

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

1 个答案:

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