Last active
January 24, 2019 14:07
-
-
Save yoshuawuyts/31dace8a9a485ed345d0b37ab4b2db25 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = class Emitter { | |
constructor () { | |
this.listeners = {} | |
} | |
on (event, listener) { | |
if (!this.listeners[event]) this.listeners[event] = [] | |
this.listeners[event].push(listener) | |
} | |
emit (event, ...args) { | |
this.listeners[event].forEach(listener => listener(...args)) | |
} | |
// BONUS | |
removeListener (event, listener) { | |
var index = this.listeners[event].indexOf(listener) | |
this.listeners[event].splice(index, 1) | |
} | |
// BONUS | |
once (event, listener) { | |
var self = this | |
this.on(event, wrapper) | |
function wrapper (...args) { | |
self.removeListener(event, wrapper) | |
listener(...args) | |
} | |
} | |
} |
@mantoni that said, your version has one less lookup. That's actually worth it. yay, changing!
@mantoni oh, haha - looks like that code might hit a snag. Reverting!
I think there may be an itty bitty bug in once
since cb
isn't a reference to the actual listener being removed.
@devinivy good catch!
maybe it's just naming, but what about renaming .removeListener
to .off
?
I've seen that in the past elsewhere already and it's a lot less to type.
By occupying only 3 instead of 14 characters, it gives other code more space to express itself
Next version of Nanobus?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mantoni oh yeah, I like that! - feel it makes for slightly less clear code though. I mean: I'm not really trying to code golf it - just trying to show off there's literally nothing to writing an event emitter in JS :D