【问题标题】:Node ES6 class event emitter function?Node ES6 类事件发射器功能?
【发布时间】:2018-01-17 23:46:48
【问题描述】:

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

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

【问题讨论】:

  • 为什么你在类声明中有语句,而不是在构造函数或其他方法中?
  • “所有实例”在您没有实例化任何实例时也意味着“没有实例”。

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


【解决方案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");
    }
}

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 2021-12-08
    • 1970-01-01
    • 2019-05-03
    • 2014-09-06
    • 2022-01-21
    • 1970-01-01
    • 2015-04-04
    • 2016-08-01
    相关资源
    最近更新 更多