Created
October 31, 2020 21:51
-
-
Save Yamo93/809cf969b1e8ab3f5e3d7ec71f347f34 to your computer and use it in GitHub Desktop.
Publish subscribe factory function
This file contains 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
function publishSubscribe() { | |
const subscribers = {}; | |
function subscribe(eventName, callback) { | |
if (!Array.isArray(subscribers[eventName])) { | |
subscribers[eventName] = []; | |
} | |
subscribers[eventName].push(callback); | |
} | |
function publish(eventName, data) { | |
if (!Array.isArray(subscribers[eventName])) { | |
return; | |
} | |
subscribers[eventName].forEach(callback => { | |
if (typeof callback === 'function') { | |
callback(data); | |
} | |
}) | |
} | |
return { | |
publish, | |
subscribe | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment