简体   繁体   English

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

[英]Node.js EventEmitter `on` event cannot “see” class property

This is a follow-up to my previous SO question . 这是我之前的SO问题的后续。 In that question, I've defined an index.js file that includes an on event handler. 在该问题中,我定义了一个包含on事件处理程序的index.js文件。 I've since updated the index.js file to look like this: 此后,我已将index.js文件更新为如下所示:

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

When I run my app, the line with this.whiteboard.write(question); 当我运行我的应用程序时,此行与this.whiteboard.write(question); generates an error. 产生一个错误。 That error is: Cannot read property 'write' of undefined . 该错误是: Cannot read property 'write' of undefined I've confirmed that this.whiteboard is undefined. 我已经确认this.whiteboard是未定义的。 My question is, how do I get access to class properties on events? 我的问题是,如何获得事件的类属性?

Thank you! 谢谢!

There shouldn't be a problem with using this.whiteboard , but your class definition is strange, actually I would expect SyntaxError by the method definition. 使用this.whiteboard应该不会有问题,但是您的类定义很奇怪,实际上我期望方法定义会产生SyntaxError

Try to change your code like this: 尝试像这样更改代码:

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

EDIT: instancing of EventEmitter 编辑: EventEmitter实例化

In the callback of any event you your this never points to your class. 在任何情况下,你的回调你this永远指向类。 try this. 尝试这个。

var self = this;
eventEmitter.on('handRaised', (question) => {
  console.log(question);
  self.whiteboard.write(question);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM