44 lines
923 B
JavaScript
44 lines
923 B
JavaScript
const pubsub = (function() { "use strict";
|
|
|
|
const topics = [
|
|
"MESSAGES_NEW",
|
|
"MESSAGES_CHANGED",
|
|
"CHANNELS_NEW",
|
|
"CHANNELS_CHANGED",
|
|
"USERS_NEW",
|
|
"USERS_CHANGED",
|
|
"CHANNEL_MEMBERS_NEW",
|
|
"CHANNEL_MEMBERS_REMOVED",
|
|
];
|
|
|
|
let subscribers = Object.create(null);
|
|
for (let topic of topics) {
|
|
subscribers[topic] = [];
|
|
}
|
|
|
|
|
|
function subscribe(topic, callback) {
|
|
assert(subscribers[topic], `Pubsub topic '${topic}' exists`);
|
|
|
|
subscribers[topic].push(callback);
|
|
}
|
|
|
|
|
|
function publish(topic, payload) {
|
|
assert(subscribers[topic], `Pubsub topic '${topic}' exists`);
|
|
|
|
const amountSubs = subscribers[topic].length;
|
|
if (amountSubs == 0) {
|
|
console.warn(`Pubsub event with topic '${topic}' without any subscribers`);
|
|
} else {
|
|
console.debug(`Pubsub event with topic '${topic}' with ${amountSubs} subscribers`);
|
|
}
|
|
for (let subscriber of subscribers[topic]) {
|
|
subscriber(payload);
|
|
}
|
|
}
|
|
|
|
|
|
return {subscribe, publish};
|
|
|
|
})();
|