szurubooru/client/js/events.js

65 lines
1.6 KiB
JavaScript
Raw Normal View History

2016-04-07 19:03:49 +02:00
'use strict';
let pendingMessages = new Map();
let listeners = new Map();
2016-04-07 19:03:49 +02:00
function unlisten(messageClass) {
listeners.set(messageClass, []);
}
2016-04-07 19:03:49 +02:00
function listen(messageClass, handler) {
if (pendingMessages.has(messageClass)) {
let newPendingMessages = [];
for (let message of pendingMessages.get(messageClass)) {
if (!handler(message)) {
newPendingMessages.push(message);
}
}
pendingMessages.set(messageClass, newPendingMessages);
2016-04-07 19:03:49 +02:00
}
if (!listeners.has(messageClass)) {
listeners.set(messageClass, []);
}
listeners.get(messageClass).push(handler);
2016-04-07 19:03:49 +02:00
}
function notify(messageClass, message) {
if (!listeners.has(messageClass) || !listeners.get(messageClass).length) {
if (!pendingMessages.has(messageClass)) {
pendingMessages.set(messageClass, []);
}
pendingMessages.get(messageClass).push(message);
2016-04-07 19:03:49 +02:00
return;
}
for (let handler of listeners.get(messageClass)) {
2016-04-07 19:03:49 +02:00
handler(message);
}
}
class EventTarget {
constructor() {
this.eventTarget = document.createDocumentFragment();
for (let method of [
'addEventListener',
'dispatchEvent',
'removeEventListener'
]) {
this[method] = this.eventTarget[method].bind(this.eventTarget);
}
}
};
2016-04-07 19:03:49 +02:00
module.exports = {
Success: 'success',
Error: 'error',
Info: 'info',
Authentication: 'auth',
SettingsChange: 'settings-change',
TagsChange: 'tags-change',
2016-04-07 19:03:49 +02:00
notify: notify,
listen: listen,
unlisten: unlisten,
EventTarget: EventTarget,
2016-04-07 19:03:49 +02:00
};