gpt4 book ai didi

javascript - Node ES6类事件发射器函数?

转载 作者:行者123 更新时间:2023-12-03 03:41:28 24 4
gpt4 key购买 nike

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

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

最佳答案

将其移至构造函数内。

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

关于javascript - Node ES6类事件发射器函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45601647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com