-
-
Save FlorianRappl/e332adfe57e236430f3d7da4ca618395 to your computer and use it in GitHub Desktop.
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 handlers = {}; | |
window.publish = (topic, message) => { | |
window.dispatchEvent(new CustomEvent('pubsub', { | |
detail: { topic, message }, | |
})); | |
}; | |
window.subscribe = (topic, handler) => { | |
const topicHandlers = handlers[topic] || []; | |
topicHandlers.push(handler); | |
handlers[topic] = topicHandlers; | |
}; | |
window.unsubscribe = (topic, handler) => { | |
const topicHandlers = handlers[topic] || []; | |
const index = topicHandlers.indexOf(handler); | |
index >= 0 && topicHandlers.splice(index, 1); | |
}; | |
window.addEventListener('pubsub', ev => { | |
const { topic, message } = ev.detail; | |
const topicHandlers = handlers[topic] || []; | |
topicHandlers.forEach(handler => handler(message)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment