Last active
January 11, 2020 05:13
-
-
Save bchiang7/4f5344511a70820100caf69212038907 to your computer and use it in GitHub Desktop.
Simple event bus in plain JS
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
// Inspired by Vue: https://alligator.io/vuejs/global-event-bus/ | |
// Sending events: EventBus.emit('clicky', clickArg); | |
// Receiving events: EventBus.on('clicky', clickArg => console.log(clickArg)); | |
const EventBus = { | |
events: {}, | |
emit(event, data) { | |
if (!this.events[event]) { | |
return; | |
} | |
this.events[event].forEach(callback => callback(data)); | |
}, | |
on(event, callback) { | |
if (!this.events[event]) { | |
this.events[event] = []; | |
} | |
this.events[event].push(callback); | |
}, | |
}; | |
export default EventBus; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment