-
-
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
commented
Mar 14, 2018
You could remove another line in on
🎉
(this.listeners[event] || this.listeners[event] = []).push(cb)
once (event, cb) {
this.on(event, (...args) => {
this.removeListener(event, cb)
cb(...args)
})
}
@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
@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?