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
const subscribers = { | |
onUserUpdate: [callbackFunction, anotherCallbackFunction], | |
onUserLogin: [callbackFunction, anotherCallbackFunction] | |
}; |
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 subscribe(eventName, callback) { | |
if (!Array.isArray(subscribers[eventName])) { | |
subscribers[eventName] = [] | |
} | |
subscribers[eventName].push(callback); | |
const index = subscribers[eventName].length - 1; | |
return () => { | |
subscribers[eventName].splice(index, 1); | |
} | |
} |
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 unsubscribe(eventName) { | |
delete subscribers[eventName]; | |
} |
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])) { |
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 publish(eventName, data) { | |
if (!Array.isArray(subscribers[eventName])) { | |
return; | |
} | |
subscribers[eventName].forEach(callback => { | |
if (typeof callback === 'function') { | |
callback(data); | |
} | |
}) | |
} |
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 subscribe(eventName, callback) { | |
if (!Array.isArray(subscribers[eventName])) { | |
subscribers[eventName] = []; | |
} | |
subscribers[eventName].push(callback); | |
} |
NewerOlder