Skip to content

Instantly share code, notes, and snippets.

@bchiang7
Last active January 11, 2020 05:13
Show Gist options
  • Save bchiang7/4f5344511a70820100caf69212038907 to your computer and use it in GitHub Desktop.
Save bchiang7/4f5344511a70820100caf69212038907 to your computer and use it in GitHub Desktop.
Simple event bus in plain JS
// 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