Skip to content

Instantly share code, notes, and snippets.

@maslade
Last active May 6, 2018 23:51
Show Gist options
  • Save maslade/d849e20c78766d175f8263b8613b08b4 to your computer and use it in GitHub Desktop.
Save maslade/d849e20c78766d175f8263b8613b08b4 to your computer and use it in GitHub Desktop.
EventEmitter bubbling through composition.
/**
* 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', () => /* ... */ );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment