Skip to content

Instantly share code, notes, and snippets.

@erikyuzwa
Forked from PierfrancescoSoffritti/eventBus.js
Last active February 10, 2019 22:01
Show Gist options
  • Save erikyuzwa/83749ec24330b78435b54b72dc067c7c to your computer and use it in GitHub Desktop.
Save erikyuzwa/83749ec24330b78435b54b72dc067c7c to your computer and use it in GitHub Desktop.
/**
* subscriptions data format:
* { eventType: { id: callback } }
*/
const subscriptions = { };
const getNextUniqueId = getIdGenerator();
function subscribe(eventType, callback) {
const id = getNextUniqueId();
if (!subscriptions[eventType]) {
subscriptions[eventType] = { };
}
subscriptions[eventType][id] = callback;
return {
unsubscribe: () => {
delete subscriptions[eventType][id];
if (Object.keys(subscriptions[eventType]).length === 0) {
delete subscriptions[eventType];
}
}
}
}
function publish(eventType, arg) {
if (!subscriptions[eventType]) {
return;
}
Object.keys(subscriptions[eventType]).forEach(key => subscriptions[eventType][key](arg));
}
function getIdGenerator() {
let lastId = 0;
return function getNextUniqueId() {
lastId += 1;
return lastId;
}
}
module.exports = { publish, subscribe };
@erikyuzwa
Copy link
Author

  • updated with some semi-colons and brackets

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment