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

This is a follow-up to my previous SO question. In that question, I've defined an index.js file that includes an on event handler. I've since updated the index.js file to look like this:

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); generates an error. That error is: Cannot read property 'write' of undefined. I've confirmed that this.whiteboard is undefined. My question is, how do I get access to class properties on events?

Thank you!

Answers:

Answer

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.

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

Answer

In the callback of any event you your this never points to your class. try this.

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.