Event emitters are everywhere: Node's EventEmitter , the DOM's addEventListener , every state library you've used. Writing one yourself takes about fifty lines, and it's a great exercise because there's one subtle bug almost every first attempt has. Let's build it, test it with Node's built-in test runner, and fix that bug on purpose.
The API
const e = new Emitter ( ) ; const stop = e . on ( 'message' , ( text ) => console . log ( text ) ) ; e . once ( 'ready' , ( ) => console . log ( 'ready, only once' ) ) ; e . emit ( 'message' , 'hello' ) ; // logs "hello", returns true stop ( ) ; // unsubscribe e . emit ( 'message' , 'again' ) ; // nothing happens, returns false
Enter fullscreen mode
Exit fullscreen mode
Four methods: on , once , off , emit . on and once return an unsubscribe function, which is much nicer than holding on to the handler just to call off later.
The implementation
class Emitter { constructor ( ) { this .…