在扩展EventEmitter的ES6类定义中设置事件侦听器

我想要一些预定义的自定义侦听器,这些自定义侦听器已经定义了这个类的定义 (就像'newListner'事件中的构build一样)。 所以我不想在构造函数中绑定它们,因为它将在该类的每个新实例上执行。

这个怎么做? 修改原型? 有没有可能?

我到目前为止:

 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'); 

你不能避免为每个实例分别注册监听器,而且在构造函数1,2中自然需要这样做。 但是,您可以避免创build新的侦听器函数:

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

1:还有其他方法,比如._events的getter。 你可以用它来做各种各样的花哨的东西,包括对“默认”听众的原型inheritance,但是这些都是过于复杂的,并且很快就把你弄得头晕眼花。 通过在构造函数中添加一些通用代码,你也可以做一些奇特的事情,也可以干净得多。
2:你也可以重写(特化)EventEmitters的init方法,但是它完全一样。

因为,就我所知, Cat发射器的多个实例不能相互通信,所以必须在构造器中为每个实例注册侦听器:

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

然后,您可以始终在不同的文件中共享您的发射器实例,方法是将其发送到您需要的脚本中。