Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Created October 30, 2017 08:39
Show Gist options
  • Save n1ru4l/670870788f6cfad86ab85e0a7c92f8dd to your computer and use it in GitHub Desktop.
Save n1ru4l/670870788f6cfad86ab85e0a7c92f8dd to your computer and use it in GitHub Desktop.
Emitter
const createEmitter = () => {
const handlersByEvent = new Map()
const on = (event, handler) => {
let handlers = handlersByEvent.get(event)
if (!handlers) {
handlers = []
handlersByEvent.set(event, handlers)
}
handlers.push(handler)
return () => {
const index = handlers.findIndex(_handler => _handler === handler)
if (index < 0) return
handlers.splice(index, 1);
}
}
const trigger = (event, ...args) => {
let handlers = handlersByEvent.get(event)
return (handlers || []).map(handler => handler(...args))
}
return {
on,
trigger,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment