From 772d7245d92f65c0b27c6c4aaaf64dc2fe9a9057 Mon Sep 17 00:00:00 2001
From: Benjamin Auder <benjamin.auder@somewhere>
Date: Fri, 16 Nov 2018 16:05:59 +0100
Subject: [PATCH] Add reconnection ability to index page

---
 public/javascripts/index.js | 42 ++++++++++++++++++++++---------------
 1 file changed, 25 insertions(+), 17 deletions(-)

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 => {
-- 
2.44.0