Skip to content

Instantly share code, notes, and snippets.

@IgorHalfeld
Created October 15, 2020 19:05
Show Gist options
  • Save IgorHalfeld/ad89fd54453f19e015554b75b6134a5e to your computer and use it in GitHub Desktop.
Save IgorHalfeld/ad89fd54453f19e015554b75b6134a5e to your computer and use it in GitHub Desktop.
function create () {
const events = {}
function off (n, callback) {
if (!events[n]) {
return
}
events[n] = events[n].filter(fn => fn !== callback)
}
function on (name, callback) {
if (!events[name]) {
events[name] = []
}
if (!callback) {
throw new Error('No callback bro')
}
if (!events[name].includes(callback)) {
events[name].push(callback)
}
return off.bind(null, name, callback)
}
function emit (n, args) {
if (!events[n]) {
return
}
events[n].forEach(fn => fn({ ...args, type: n }))
}
function once (name, callback) {
on(name, (args) => {
callback(args)
off(name, callback.bind(null, args))
})
return off.bind(null, name, callback)
}
return { on, emit, off, events, once }
}
module.exports = { create }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment