Skip to content

Instantly share code, notes, and snippets.

@l-portet
Last active April 4, 2024 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save l-portet/d77babf5fa102d27ff0985bf31d8b591 to your computer and use it in GitHub Desktop.
Save l-portet/d77babf5fa102d27ff0985bf31d8b591 to your computer and use it in GitHub Desktop.
utility hook for event communication in React components
import { useEffect, useState } from 'react';
type Callback = (data?: any) => void;
class EventBus<E extends string = string> {
events: Partial<Record<E, Callback[]>>;
constructor() {
this.events = {};
}
on(event: E, callback: Callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event]!.push(callback);
}
off(event: E, callback: Callback) {
if (!this.events[event]) {
return;
}
this.events[event] = this.events[event]!.filter((fn) => fn !== callback);
}
clear() {
this.events = {};
}
emit(event: E, data?: any) {
if (!this.events[event]) {
return;
}
this.events[event]!.forEach((callback) => callback(data));
}
}
export default function useEventBus<E extends string = string>() {
const [bus] = useState(new EventBus<E>());
useEffect(() => () => bus.clear(), []);
return bus;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment