Skip to content

Instantly share code, notes, and snippets.

@trafficinc
Last active August 5, 2021 18:30
Show Gist options
  • Save trafficinc/80a73b8a32f26e1ab02909f10820a5bf to your computer and use it in GitHub Desktop.
Save trafficinc/80a73b8a32f26e1ab02909f10820a5bf to your computer and use it in GitHub Desktop.
Event Bus for use in React/Vanilla
/*
To Use:
:: Component A ::
import eventBus from "./EventBus";
- Dispatch an Event to component B -
eventBus.dispatch("aResource", { resource: this.state.resource });
:: Component B ::
import eventBus from "./EventBus";
- receive the dispatched event and handle data from component A -
useEffect(() => {
...
eventBus.on("aResource", (data) => {
console.log(data.resource)
});
...
}
:: EventBus.js ::
*/
const eventBus = {
on(event, callback) {
document.addEventListener(event, (e) => callback(e.detail));
},
dispatch(event, data) {
document.dispatchEvent(new CustomEvent(event, { detail: data }));
},
remove(event, callback) {
document.removeEventListener(event, callback);
},
};
export default eventBus;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment