将事件发射器与节点中每个 ES6 class 的实例连接
Connect event emitter with instance of each ES6 class in node
我正在尝试将 class 的每个实例与一个事件发射器相关联。我正在尝试以下操作:
const events = require("events");
const eventEmitter = new events.EventEmitter();
class Camera {
constructor(ip) {
this.ip = ip;
eventEmitter.on("recordVideo", function() {
this.recordClip();
});
}
recordClip() {
console.log("record " + this.ip);
}
}
var cam = new Camera("0.0.0.0");
eventEmitter.emit("recordVideo");
但我回来了:
TypeError: this.recordClip is not a function
如何让我的 class 的每个实例监听事件?
这是因为回调函数中的上下文没有引用您期望的内容。添加箭头函数。
const events = require("events");
const eventEmitter = new events.EventEmitter();
class Camera {
constructor(ip) {
this.ip = ip;
eventEmitter.on("recordVideo", () => {
this.recordClip();
});
}
recordClip() {
console.log("record " + this.ip);
}
}
var cam = new Camera("0.0.0.0");
eventEmitter.emit("recordVideo");
这是一些文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
你的问题是 this
在事件发射器的上下文中,而不是 class。因此,eventEmitter
没有 recordClip
作为方法。您需要使用箭头函数在词法上绑定您的回调:
(个人认为这是最好的,也是最modern/readable的方法)
eventEmitter.on("recordVideo", () => {
this.recordClip();
});
或者,您需要绑定适当的范围:
eventEmitter.on("recordVideo", function() {
this.recordClip();
}).bind(this);
或者您可以通过 self
方法引用 this
:
class Camera {
constructor(ip) {
this.ip = ip;
const self = this; //assign this to self
eventEmitter.on("recordVideo", function() {
self.recordClip(); //use self, not this here
});
}
recordClip() {
console.log("record " + this.ip);
}
}
我正在尝试将 class 的每个实例与一个事件发射器相关联。我正在尝试以下操作:
const events = require("events");
const eventEmitter = new events.EventEmitter();
class Camera {
constructor(ip) {
this.ip = ip;
eventEmitter.on("recordVideo", function() {
this.recordClip();
});
}
recordClip() {
console.log("record " + this.ip);
}
}
var cam = new Camera("0.0.0.0");
eventEmitter.emit("recordVideo");
但我回来了:
TypeError: this.recordClip is not a function
如何让我的 class 的每个实例监听事件?
这是因为回调函数中的上下文没有引用您期望的内容。添加箭头函数。
const events = require("events");
const eventEmitter = new events.EventEmitter();
class Camera {
constructor(ip) {
this.ip = ip;
eventEmitter.on("recordVideo", () => {
this.recordClip();
});
}
recordClip() {
console.log("record " + this.ip);
}
}
var cam = new Camera("0.0.0.0");
eventEmitter.emit("recordVideo");
这是一些文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
你的问题是 this
在事件发射器的上下文中,而不是 class。因此,eventEmitter
没有 recordClip
作为方法。您需要使用箭头函数在词法上绑定您的回调:
(个人认为这是最好的,也是最modern/readable的方法)
eventEmitter.on("recordVideo", () => {
this.recordClip();
});
或者,您需要绑定适当的范围:
eventEmitter.on("recordVideo", function() {
this.recordClip();
}).bind(this);
或者您可以通过 self
方法引用 this
:
class Camera {
constructor(ip) {
this.ip = ip;
const self = this; //assign this to self
eventEmitter.on("recordVideo", function() {
self.recordClip(); //use self, not this here
});
}
recordClip() {
console.log("record " + this.ip);
}
}