Last active
August 5, 2021 20:07
-
-
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)
This file contains hidden or 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
/** | |
* 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