Last active
May 12, 2020 15:57
-
-
Save Ivannnnn/f9281919ec04e769088a60be44ebfed4 to your computer and use it in GitHub Desktop.
This file contains 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
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 } | |
} |
This file contains 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
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 } | |
} |
This file contains 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
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