Created
March 10, 2022 18:39
-
-
Save VasiliyRusin/6b1d277fdbb179cbeefe7d4598a211df to your computer and use it in GitHub Desktop.
Simple event bus
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
const bus = {}; | |
function on(event, callback) { | |
const id = Symbol(''); | |
if (!bus[event]) bus[event] = {}; | |
bus[event][id] = callback; | |
return { | |
unsubscribe: () => { | |
delete bus[event][id]; | |
if (Object.hasOwnProperty(bus[event])) { | |
delete bus[event]; | |
} | |
} | |
} | |
} | |
function emmit(event, args) { | |
if (!bus[event]) return; | |
Object | |
.keys(bus[event]) | |
.forEach(key => bus[event][key](args)) | |
} | |
export { | |
on, | |
emmit | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment