/** * Demonstrates a method for creating bubbling behavior through EventEmitter * composition. With this method a parent class (ConsumerClass) is composed * of instances of helper classes (HelpfulClass), and wants to bubble all of * their events up to itself. The goal is that client code can listen at the * parent level (to receive all events) or at the instance level. * * Limitations without a little more scaffolding: * - no context for determining where an event originated from. * - this implementation assumes that HelpfulClass.emitter will not have * listeners attached at the time it's replaced, as they would not be * copied into the new upstream emitter. */ const EventEmitter = require('events').EventEmitter; class HelpfulClass { constructor() { this.emitter = new EventEmitter; } someFunc() { this.emitter.trigger('doingImportantThings'); // ... this.emitter.trigger('didImportantThings'); } } class ConsumerClass { constructor() { this.helperA = new HelpfulClass(/* ... */); this.helperB = new HelpfulClass(/* ... */); this.helperA.emitter = this.helperB.emitter = this.emitter = new EventEmitter; } } function main() { const mainDoer = new ConsumerClass(); mainDoer.on('didImportantThings', () => /* ... */ ); }