Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
|
development:javascript:react:pub_sub [2020/02/28 13:38] kalenpw created |
— (current) | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | ====== Pub Sub / Event Bus ====== | ||
| - | Useful for when you don't want to include Redux, but would like to have events that can be triggered and listened to across unrelated components. | ||
| - | ---- | ||
| - | |||
| - | ===== 1) Create EventBus ===== | ||
| - | I usually put this in '' | ||
| - | <file javascript event_bus.js> | ||
| - | const EventBus = { | ||
| - | /** | ||
| - | * events stored as object with each field being an event | ||
| - | */ | ||
| - | events: {}, | ||
| - | /** | ||
| - | * Call all callbacks for given event | ||
| - | * @param {string} event name of event | ||
| - | * @param {*} data data sent to all event callbacks | ||
| - | */ | ||
| - | dispatch: (event, data) => { | ||
| - | if (!EventBus.events[event]) { | ||
| - | return; | ||
| - | } | ||
| - | EventBus.events[event].forEach(callback => callback(data)); | ||
| - | }, | ||
| - | /** | ||
| - | * @param event - the name of the event | ||
| - | * @param callback - the function to be called | ||
| - | */ | ||
| - | subscribe: (event, callback) => { | ||
| - | if (!EventBus.events[event]) { | ||
| - | EventBus.events[event] = []; | ||
| - | } | ||
| - | EventBus.events[event].push(callback); | ||
| - | }, | ||
| - | /** | ||
| - | * Must be called with the exact same callback as subscribe | ||
| - | * as we match functions by their .toString() | ||
| - | * @param event - the name of the event | ||
| - | * @param callback - the function to be removed | ||
| - | */ | ||
| - | unsubscribe: | ||
| - | let newEvents = EventBus.events[event].filter((event) => { | ||
| - | // hack to ensure we remove the right event | ||
| - | if (!(callback.toString() == event.toString())) { | ||
| - | return event; | ||
| - | } | ||
| - | }) | ||
| - | EventBus.events[event] = newEvents; | ||
| - | } | ||
| - | } | ||
| - | |||
| - | export default EventBus; | ||
| - | </ | ||