diff --git a/src/components/mixins/websocket.js b/src/components/mixins/websocket.js index bb959886..b0e450dd 100644 --- a/src/components/mixins/websocket.js +++ b/src/components/mixins/websocket.js @@ -34,19 +34,45 @@ export default { methods: { initWebSocket: function(url, params, onmessage, onerror, onclose) { this.websock = new WebSocket(getWsURL() + url); + + // proxy function that wait readyState === 1 + const waitForConnection = (callback, interval) => { + if (this.websock.readyState === 1) { + callback(); + } else { + setTimeout(() => { + waitForConnection(callback, interval); + }, interval); + } + } this.websock.onopen = () => { - this.websock.send(JSON.stringify(params)); + waitForConnection(() => { + this.websock.send(JSON.stringify(params)); + }, 500); }; + this.websock.onmessage = ret => { onmessage(JSON.parse(ret.data)); }; + this.websock.onerror = onerror; this.websock.onclose = onclose; + }, + closeWebSocket: function() { + if (this.websock) { + this.websock.close(); + } } }, - destroyed: function() { - if (this.websock) { - this.websock.close(); + watch: { + $route: function() { + this.closeWebSocket(); } + }, + destroyed: function() { + this.closeWebSocket(); + }, + beforeRouteUpdate: function() { + this.closeWebSocket(); } }