From: Benjamin Auder Date: Fri, 16 Nov 2018 15:05:59 +0000 (+0100) Subject: Add reconnection ability to index page X-Git-Url: https://git.auder.net/%7B%7B%20asset%28%27mixstore/css/user/doc/pieces/%3C?a=commitdiff_plain;h=772d7245d92f65c0b27c6c4aaaf64dc2fe9a9057;p=vchess.git Add reconnection ability to index page --- diff --git a/public/javascripts/index.js b/public/javascripts/index.js index a05ad475..e24995be 100644 --- a/public/javascripts/index.js +++ b/public/javascripts/index.js @@ -1,24 +1,9 @@ -const url = socketUrl; -// random enough (TODO: function) -const sid = (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase(); -const conn = new WebSocket(url + "/?sid=" + sid + "&page=index"); - -conn.onmessage = msg => { - const data = JSON.parse(msg.data); - if (data.code == "counts") - //V.counts = data.counts; - Vue.set(V, "counts", data.counts); - else if (data.code == "increase") - V.counts[data.vname]++; - else if (data.code == "decrease") - V.counts[data.vname]--; -} - -let V = new Vue({ +new Vue({ el: "#indexPage", data: { counts: {}, curPrefix: "", + conn: null, }, computed: { sortedCounts: function () { @@ -37,6 +22,29 @@ let V = new Vue({ }); }, }, + created: function() { + const url = socketUrl; + // random enough (TODO: function) + const sid = (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase(); + this.conn = new WebSocket(url + "/?sid=" + sid + "&page=index"); + const socketMessageListener = msg => { + const data = JSON.parse(msg.data); + if (data.code == "counts") + this.counts = data.counts; + else if (data.code == "increase") + this.counts[data.vname]++; + else if (data.code == "decrease") + this.counts[data.vname]--; + }; + const socketCloseListener = () => { + console.log("Lost connection -- reconnect"); + this.conn = new WebSocket(url + "/?sid=" + sid + "&page=index"); + this.conn.addEventListener('message', socketMessageListener); + this.conn.addEventListener('close', socketCloseListener); + }; + this.conn.onmessage = socketMessageListener; + this.conn.onclose = socketCloseListener; + }, mounted: function() { // Handle key stroke document.onkeydown = event => {