alexsandersarmento / react-native-event-emitter

MIT License
4 stars 1 forks source link

Multiple Listeners For Same EventType #1

Open cenkakay opened 1 month ago

cenkakay commented 1 month ago

Firstly thank you for this library. What happens when we listen same event from two different component? I look at the source code, looks like this library works for one listener to one eventType. Am I correct?

cenkakay commented 1 month ago
let listenersMap: { [id: string]: ((...params: any[]) => void)[] } = {};

export const addListener = (eventName: string, listener: (...params: any[]) => void) => {
  if (listenersMap[eventName]) {
    listenersMap[eventName].push(listener);
  } else {
    listenersMap[eventName] = [listener];
  }
};

export const removeListener = (eventName: string, listener: (...params: any[]) => void) => {
  listenersMap[eventName].filter((l) => l !== listener);
};

export const removeAllListeners = () => {
  listenersMap = {};
};

export const notify = <T = any>(eventName: string, ...params: T[]) => {
  const listener = listenersMap[eventName];
  if (listener && listener.length > 0) {
    listener.forEach((l) => l(...params));
  }
};

What do you think for this?