Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Last active May 12, 2020 15:57
Show Gist options
  • Save Ivannnnn/f9281919ec04e769088a60be44ebfed4 to your computer and use it in GitHub Desktop.
Save Ivannnnn/f9281919ec04e769088a60be44ebfed4 to your computer and use it in GitHub Desktop.
const createEventBus = () => {
const subscribers = {}
let counter = 0
const on = (name, cb) => {
if (!subscribers[name]) subscribers[name] = {}
subscribers[name][++counter] = cb
return btoa(name + '.' + counter)
}
const off = (id) => {
const [name, prop] = atob(id).split('.')
subscribers[name] && delete subscribers[name][prop]
}
const emit = (name, ...args) => {
if (subscribers[name])
Object.values(subscribers[name]).forEach((cb) => cb(...args))
}
return { on, off, emit }
}
const createEventBus = () => {
const subscribers = {}
const on = (name, cb) => {
subscribers[name]
? subscribers[name].push(cb)
: (subscribers[name] = [cb])
}
const off = () => {}
const emit = (name, ...args) => {
if (subscribers[name]) subscribers[name].forEach((cb) => cb(...args))
}
return { on, off, emit }
}
const events = (() => {
const subscribers = {}
const on = (eventName, cb) => {
subscribers[eventName]
? subscribers[eventName].push(cb)
: (subscribers[eventName] = [cb])
}
const emit = (eventName, ...args) => {
if (subscribers[eventName]) {
subscribers[eventName].forEach(cb => cb(...args))
}
}
return { on, emit }
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment