diff --git a/frontend/src/stores.js b/frontend/src/stores.js index 52112d9..a9c9590 100644 --- a/frontend/src/stores.js +++ b/frontend/src/stores.js @@ -4,30 +4,20 @@ import gateway, { GatewayEventType } from "./gateway"; class Store { constructor() { this._handlers = []; - this._didInit = false; - } - - _tryInit() { - if (!this._didInit && this._init) { - this._init(); - this._didInit = true; - } } subscribe(handler) { - this._tryInit(); - const newLength = this._handlers.push(handler); const handlerIndex = newLength - 1; - handler(this._value); + handler(this.value); return () => { this._handlers.splice(handlerIndex, 1); }; } - _dispatchUpdate() { + updated() { this._handlers.forEach(e => { - e(this._value); + e(this.value); }); } } @@ -36,47 +26,38 @@ class ChannelsStore extends Store { constructor() { super(); - this._value = []; - } - - _init() { - const channels = gateway.channels; - if (channels) { - this._value = channels; - } + this.value = gateway.channels || []; gateway.subscribe(GatewayEventType.Ready, ({ channels }) => { - if (channels) { - this._value = channels; - } + this.value = channels; - this._dispatchUpdate(); + this.updated(); }); gateway.subscribe(GatewayEventType.ChannelCreate, (channel) => { - this._value.push(channel); + this.value.push(channel); - this._dispatchUpdate(); + this.updated(); }); gateway.subscribe(GatewayEventType.ChannelDelete, ({ id }) => { - const index = this._value.findIndex(e => e.id === id); + const index = this.value.findIndex(e => e.id === id); if (!index) return; - this._value.splice(index, 1); + this.value.splice(index, 1); - this._dispatchUpdate(); + this.updated(); }); gateway.subscribe(GatewayEventType.ChannelUpdate, (data) => { - const index = this._value.findIndex(e => e.id === data.id); + const index = this.value.findIndex(e => e.id === data.id); if (!index) return; - if (!this._value[index]) + if (!this.value[index]) return; - this._value[index] = data; + this.value[index] = data; - this._dispatchUpdate(); + this.updated(); }); } } @@ -84,27 +65,22 @@ class ChannelsStore extends Store { class GatewayStatusStore extends Store { constructor() { super(); - this._value = { open: false, ready: false }; - } - - _init() { - this._value.open = gateway.open; - this._value.ready = gateway.authenticated; + this.value = { open: gateway.open, ready: gateway.authenticated }; gateway.subscribe(GatewayEventType.Open, () => { - this._value.open = true; - this._dispatchUpdate(); + this.value.open = true; + this.updated(); }); gateway.subscribe(GatewayEventType.Close, () => { - this._value.open = false; - this._value.ready = false; - this._dispatchUpdate(); + this.value.open = false; + this.value.ready = false; + this.updated(); }); gateway.subscribe(GatewayEventType.Ready, () => { - this._value.ready = true; - this._dispatchUpdate(); + this.value.ready = true; + this.updated(); }); } }