本文介绍了节点ES6类的事件发射器函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

似乎从未调用过recordClip函数.这可能吗?

The recordClip function never seems to be called. Is this possible?

我还尝试了运行this.recordClip而不是recordClip.

I also tried running this.recordClip instead of recordClip.

推荐答案

将其移动到构造函数中.

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

这篇关于节点ES6类的事件发射器函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 18:04