Skip to content

Instantly share code, notes, and snippets.

@FlorianRappl
Created February 27, 2020 14:14
Show Gist options
  • Save FlorianRappl/e332adfe57e236430f3d7da4ca618395 to your computer and use it in GitHub Desktop.
Save FlorianRappl/e332adfe57e236430f3d7da4ca618395 to your computer and use it in GitHub Desktop.
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