Node.js EventEmitter`on`事件无法“看到”类属性

时间:2019-03-19 12:00:56

标签: javascript eventemitter

这是我的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是未定义的。我的问题是,如何获得事件的类属性?

谢谢!

2 个答案:

答案 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);
});