Menu

Build a tiny event emitter in 50 lines (and the one bug most versions have)
📰

Build a tiny event emitter in 50 lines (and the one bug most versions have)

DEV Community: node·Rich Polo·about 2 hours ago
#SdNu3Rnd
#devtonodejs#devto#dev#event#const
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.