这是我的previous SO question的后续活动。在这个问题中,我定义了一个包含index.js
事件处理程序的on
文件。此后,我已经将index.js
文件更新为:
index.js
const EventEmitter = require('events');
const Student = require('./student');
const Whiteboard = require('./whiteboard');
class Classroom {
constructor() {
this.whiteboard = new Whiteboard();
}
async function start() {
eventEmitter.on('newListener', (event, listener) => {
console.log(`Added ${event} listener.`);
});
eventEmitter.on('handRaised', (question) => {
console.log(question);
this.whiteboard.write(question);
});
for (let i=0; i<10; i++) {
let student = new Student(`Student #${i+1}`);
student.attend();
}
}
}
运行我的应用程序时,带有this.whiteboard.write(question);
的行会产生错误。该错误是:Cannot read property 'write' of undefined
。我已经确认this.whiteboard
是未定义的。我的问题是,如何获得事件的类属性?
谢谢!
答案 0 :(得分:0)
使用this.whiteboard
应该没有问题,但是您的类定义很奇怪,实际上我希望方法定义SyntaxError
。
尝试这样更改代码:
const EventEmitter = require('events');
const Student = require('./student');
const Whiteboard = require('./whiteboard');
const eventEmitter = new EventEmitter(); /* create an emitter instance */
class Classroom {
constructor() {
this.whiteboard = new Whiteboard();
}
async start() { /* no 'function' here */
eventEmitter.on('newListener', (event, listener) => {
console.log(`Added ${event} listener.`);
});
eventEmitter.on('handRaised', (question) => {
console.log(question);
this.whiteboard.write(question);
});
for (let i=0; i<10; i++) {
let student = new Student(`Student #${i+1}`);
student.attend();
}
}
}
编辑:EventEmitter
的实例
答案 1 :(得分:-1)
在任何事件的回调中,您的this
都不会指向您的班级。试试这个。
var self = this;
eventEmitter.on('handRaised', (question) => {
console.log(question);
self.whiteboard.write(question);
});