class App { constructor() { this.data = {users: {}}; this.eventListeners = {'users.patch': []}; this.promises = {users: {}}; this.socket = io({transports: ['websocket'], upgrade: false}); this.socket.on('users.patch', patch => this.usersPatchHandler(patch)); } get users() { return this.data.users; } addEventListener(type, listener) { if (!(type in this.eventListeners)) { throw `Unknown event type: ${type}`; } this.eventListeners[type].push(listener); } flash(message, category) { let iconPrefix; let toast; let toastCloseActionElement; switch (category) { case 'corpus': iconPrefix = 'book'; break; case 'error': iconPrefix = 'error'; break; case 'job': iconPrefix = 'J'; break; default: iconPrefix = 'notifications'; break; } toast = M.toast( { html: ` ${iconPrefix}${message} `.trim() } ); toastCloseActionElement = toast.el.querySelector('.toast-action[data-action="close"]'); toastCloseActionElement.addEventListener('click', () => {toast.dismiss();}); } getUserById(userId) { if (userId in this.promises.users) { return this.promises.users[userId]; } this.promises.users[userId] = new Promise((resolve, reject) => { this.socket.emit('users.user.get', userId, response => { if (response.code === 200) { this.data.users[userId] = response.payload; resolve(this.data.users[userId]); } else { reject(response); } }); }); return this.promises.users[userId]; } usersPatchHandler(patch) { let listener; this.data = jsonpatch.applyPatch(this.data, patch).newDocument; //this.data = jsonpatch.apply_patch(this.data, patch); for (listener of this.eventListeners['users.patch']) {listener(patch);} } }