Skip to content

Instantly share code, notes, and snippets.

@tranquan
Last active August 5, 2021 20:07
Show Gist options
  • Save tranquan/adb3c3ff7a25a919e7cbc67f2980096f to your computer and use it in GitHub Desktop.
Save tranquan/adb3c3ff7a25a919e7cbc67f2980096f to your computer and use it in GitHub Desktop.
A simple way to broardcast message in react app, use for low level layer to communicate with higher level (app/ui layer)
/**
* A simplify version of https://github.com/primus/eventemitter3
*/
const listenersMap: { [id: string]: Array<(...params: any[]) => void> } = {};
function addListener(eventName: string, listener: (...params: any[]) => void) {
listenersMap[eventName] = listenersMap[eventName] || [];
listenersMap[eventName].push(listener);
}
function removeListener(eventName: string, listener: (...params: any[]) => void) {
let lis = listenersMap[eventName];
if (!lis) return;
for (let i = lis.length - 1; i >= 0; i--) {
if (lis[i] === listener) {
lis.splice(i, 1);
break;
}
}
}
function removeAllListeners(eventName: string) {
listenersMap[eventName] = [];
}
function notify<T = any>(eventName: string, ...params: T[]) {
let listeners = listenersMap[eventName];
if (!listeners) return false;
listeners.forEach(fnc => {
fnc(...params);
});
return true;
}
const EventEmitter = {
addListener,
removeListener,
removeAllListeners,
notify,
};
export default EventEmitter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment