Last active
August 5, 2021 18:30
-
-
Save trafficinc/80a73b8a32f26e1ab02909f10820a5bf to your computer and use it in GitHub Desktop.
Event Bus for use in React/Vanilla
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
/* | |
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