diff --git a/js/Legacy.js b/js/Legacy.js index 263b9714..b705a3f7 100644 --- a/js/Legacy.js +++ b/js/Legacy.js @@ -20,12 +20,13 @@ class Poller { * Wrapper around what would regularly be socket communications, but handled * through a POST-based polling loop */ - constructor(app) { - this.app = app; + constructor(correctPathname, _handleMessage, onConnect, onDisconnect) { + this.onConnect = onConnect; + this.onDisconnect = onDisconnect; var url = window.location; this.target = - url.protocol + '//' + url.host + app.correctPathname() + 'socket_wrap'; - this.handleMessage = app._handleMessage; + url.protocol + '//' + url.host + correctPathname() + 'socket_wrap'; + this.onmessage = _handleMessage; fetch(this.target) .then((res) => { return res.json(); @@ -38,15 +39,11 @@ class Poller { finishSetup = (sid) => { this.sid = sid; this.poller_id = window.setInterval(() => this.poll(), POLLING_INTERVAL); - this.app.setState({ - connected: true, - }); + this.onConnect(true); }; close = () => { - this.app.setState({ connected: false }, () => { - this.app._socket = null; - }); + this.onDisconnect(); window.clearInterval(this.poller_id); }; @@ -82,7 +79,7 @@ class Poller { // Must re-encode message as handle message expects json // in this particular format from sockets // TODO Could refactor message parsing out elsewhere. - this.handleMessage({ data: msg }); + this.onmessage({ data: msg }); }); } }, diff --git a/js/main.js b/js/main.js index 3457a86b..37c63722 100644 --- a/js/main.js +++ b/js/main.js @@ -254,11 +254,29 @@ function App() { if (_socket.current) { return; } + + const _onConnect = () => setConnected(true); + const _onDisconnect = () => { + // check if is mounted. error can appear on unmounted component + if (mounted.current) { + callbacks.current.push(() => { + _socket.current = null; + }); + setConnected(false); + } + }; + // eslint-disable-next-line no-undef if (USE_POLLING) { - _socket.current = new Poller(this); + _socket.current = new Poller( + correctPathname, + _handleMessage, + _onConnect, + _onDisconnect + ); return; } + var url = window.location; var ws_protocol = null; if (url.protocol == 'https:') { @@ -271,21 +289,8 @@ function App() { ); socket.onmessage = _handleMessage; - - socket.onopen = () => { - setConnected(true); - }; - - socket.onerror = socket.onclose = () => { - // check if is mounted. error can appear on unmounted component - if (mounted.current) { - setConnected(false); - callbacks.current.push(() => { - socket.current = null; - }); - } - }; - + socket.onopen = _onConnect; + socket.onerror = socket.onclose = _onDisconnect; _socket.current = socket; };