Great article.
Another approach for unsubscribe is using Map, like this:
function PubSub() { const subscribers = {}; function subscribe(eventName, callback) { if (!subscribers[eventName]) { subscribers[eventName] = new Map(); } const key = `key${Math.random()}`; subscribers[eventName].set(key, callback); return { unsubscribe: () => subscribers[eventName].delete(key), }; } function publish(eventName, data) { if (!subscribers[eventName]) return; subscribers[eventName].forEach(callback => callback(data)); } return { subscribe, publish, }; }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Great article.
Another approach for unsubscribe is using Map, like this: