Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set event listeners in ES6 class definition that extends EventEmitter

I want some predefined custom listeners, that are defined already with the definition of the class (like the build in 'newListner' event). So I don't want to just bind them in the constructor because it would be executed on every new instance of that class.

How to do this? Modify the prototype? Is it possible at all?

What I have so far:

class Cat extends EventEmitter {
  // just added for demonstration, I don't want this!
  constructor() {
    super();
    // does fire
    this.on('wave', function() { console.log('constructor wave'); });
  }
}
// compiles but does not fire
Cat.prototype.on('wave', function() { console.log('prototype wave'); });

var cat = new Cat();
cat.emit('wave');
like image 468
flori Avatar asked Mar 04 '16 13:03

flori


People also ask

What is returned by emitter on event listener method?

listenerCount(emitter, event) Returns the number of listeners for a given event.

What happens if an error event is emitted through an EventEmitter and nothing listens to it?

If an EventEmitter does not have at least one listener registered for the error event, and an error event is emitted, the error is thrown, a stack trace is printed, and the Node. js process exits.

Can you add an event listener to a class in JavaScript?

Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements. Use the addEventListener() method to add an event listener to each element.

How are functions called when an EventEmitter object emits an event?

When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and discarded. The following example shows a simple EventEmitter instance with a single listener.


1 Answers

You cannot avoid registering the listeners separately for every instance, and the natural place to do that is in the constructor1, 2. However, you can avoid creating new listener functions:

class Cat extends EventEmitter {
  constructor() {
    super();
    this.on('wave', this.onWave);
  }
  onWave() {
    console.log('prototype wave');
  }
}

var cat = new Cat();
cat.emit('wave');

1: There are other ways, like a getter for ._events. You could do all kinds of fancy stuff with that, including prototypical inheritance for "default" listeners, but those are totally overcomplicated and get over your head quickly. You can do fancy things as well - and much cleaner - by just putting some generic code in the constructor.
2: You could also override (specialise) the init method of EventEmitters, but it comes down to exactly the same.

like image 175
Bergi Avatar answered Nov 02 '22 09:11

Bergi