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) | |
} | |
} | |
} |
@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
I think there may be an itty bitty bug in
once
sincecb
isn't a reference to the actual listener being removed.