Skip to content

Instantly share code, notes, and snippets.

@yoshuawuyts
Last active January 24, 2019 14:07
Show Gist options
  • Save yoshuawuyts/31dace8a9a485ed345d0b37ab4b2db25 to your computer and use it in GitHub Desktop.
Save yoshuawuyts/31dace8a9a485ed345d0b37ab4b2db25 to your computer and use it in GitHub Desktop.
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)
}
}
}
@yoshuawuyts
Copy link
Author

@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

@yoshuawuyts
Copy link
Author

@mantoni that said, your version has one less lookup. That's actually worth it. yay, changing!

@yoshuawuyts
Copy link
Author

@mantoni oh, haha - looks like that code might hit a snag. Reverting!

@devinivy
Copy link

devinivy commented Mar 14, 2018

I think there may be an itty bitty bug in once since cb isn't a reference to the actual listener being removed.

@yoshuawuyts
Copy link
Author

@devinivy good catch!

@serapath
Copy link

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

@bcomnes
Copy link

bcomnes commented Mar 21, 2018

Next version of Nanobus?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment