Use a $watch-based system to register subscribe handlers when the events component is not yet ready instead of relying on setTimeout hacks

This commit is contained in:
Fabio Manganiello 2020-11-28 00:29:22 +01:00
parent 8f477fa335
commit 1036358b28
3 changed files with 27 additions and 4 deletions

View File

@ -17,6 +17,7 @@ export default {
data() { data() {
return { return {
ws: null, ws: null,
initialized: false,
pending: false, pending: false,
opened: false, opened: false,
timeout: null, timeout: null,
@ -125,6 +126,7 @@ export default {
this.ws.onopen = this.onOpen this.ws.onopen = this.onOpen
this.ws.onerror = this.onError this.ws.onerror = this.onError
this.ws.onclose = this.onClose this.ws.onclose = this.onClose
this.initialized = true
}, },
subscribe(msg) { subscribe(msg) {

View File

@ -118,7 +118,7 @@ export default {
}, },
mounted() { mounted() {
setTimeout(this.registerHandlers, 10000) this.registerHandlers()
}, },
} }
</script> </script>

View File

@ -3,11 +3,32 @@ import { bus } from "@/bus";
export default { export default {
name: "Events", name: "Events",
computed: {
_eventsReady() {
return this.$root.$refs.events?.initialized
},
},
methods: { methods: {
subscribe(handler, ...events) { subscribe(handler, ...events) {
bus.emit('subscribe', { const subFunc = () => {
events: events, bus.emit('subscribe', {
handler: handler, events: events,
handler: handler,
})
}
if (this._eventsReady) {
subFunc()
return
}
const self = this
const unwatch = this.$watch( () => self._eventsReady, (newVal) => {
if (newVal) {
subFunc()
unwatch()
}
}) })
}, },
} }