48 lines
1.2 KiB
JavaScript
48 lines
1.2 KiB
JavaScript
const pubsub = (function() { "use strict";
|
|
|
|
const topics = [
|
|
"MESSAGES_NEW", // {endpoint, channel_id, create_at, user_id, message}
|
|
"MESSAGES_CHANGED",
|
|
"CHANNELS_RELOADED", //
|
|
"CHANNEL_UPDATED", // {endpoint, channel}
|
|
"CHANNEL_UNREAD_UPDATED", // {endpoint, channel_id, unread, mentions}
|
|
"CHANNEL_LAST_POST_TIME_UPDATED", // {endpoint, channel_id, time}
|
|
"USERS_NEW",
|
|
"USERS_CHANGED",
|
|
"CHANNEL_MEMBERS_NEW",
|
|
"CHANNEL_MEMBERS_REMOVED",
|
|
"CHANNEL_READ", // {endpoint, channel_id}
|
|
"WINDOW_FOCUSED",
|
|
];
|
|
|
|
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};
|
|
|
|
})();
|