Search code examples
javascriptecmascript-6eventemitter

Can I use this.on to listen to events in EventEmitter? Looking for correct usage of Eventmitter in class in javascript


I am using EventEmitter3 which is an event module in my javascript code. It works just like the event module in Node.js. But I am facing problems to use it correctly.

Normally if I use the module in my code, I would create an object of the EventEmitter and then use object.emit to fire the events and object.on to listen to the events. And what I normally do is put object.on in another class so it works perfectly.

Now I try to organize my code in ES6 classes. So I extend EventEmitter in my customized class. Assume it is called ClassA, which is a subclass of EventEmitter. If I listen to its own event in the class definition, like this:

import EventEmitter from 'eventemitter3';

class ClassA extends EventEmitter {
  constructor() {
    ...
  }

  method() {
    this.emit('send');
  }

  this.on('send', function(data) {
    // Do something with data
  });
}

I am getting an Unexpected token error on this.on line. But I am not sure how to listen to the class's own event inside the class or is this even doable? Do I have to put the listeners outside of the class definition?


Solution

  • You need to put calls that are supposed to run for each instance inside the constructor:

    class ClassA extends EventEmitter {
      constructor() {
        super()
        …
        this.on('send', data => {
          // Do something with data
        });
      }
    
      method() {
        this.emit('send');
      }
    }
    

    Otherwise let the creator of the instances listen to the events, or listen/unlisten from within your class's methods.