Set event listeners in an ES6 class definition that extends EventEmitter

I need certain predefined user listeners that are already defined with the class definition (for example, the assembly 'newListner' ). Therefore, I do not want to just bind them in the constructor, because it will be executed on every new instance of this class.

How to do it? Change prototype? Is it possible at all?

What I still have:

 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'); 
+8
javascript ecmascript-6 extends event-listener
source share
2 answers

You can not register the listeners separately for each instance, and the natural place for this is in the constructor 1, 2 . However, you can not create new listening 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 such as getter for ._events . You can do all kinds of fancy things with this, including prototype inheritance for listeners by default, but they are completely complex and quickly cope with your head. You can also do fancy things - and much cleaner - just by putting some common code in the constructor.
2: You can also override (specialize) the init method for EventEmitters, but it comes down to the same.

+6
source share

Since, as far as I see, several instances of the Cat emitter cannot communicate with each other, you will need to register a listener for each instance in the constructor:

 class Cat extends EventEmitter { constructor() { super(); this.on('wave', function() { console.log('constructor wave'); }); } } var cat = new Cat(); cat.emit('wave'); 

You can then share your emitter instance in different files using require with it in the scripts you need.

0
source share

All Articles