const webSocket = new WebSocket('wss://echo.websocket.org'); //Event listeners are the pillars upon which WebSockets are built. This event fires when the WebSocket is considered 'OPEN', //which means that it has connected successfully. webSocket.addEventListener('open', function(event) { console.log('websocket connected successfully') //log this into the browser console so we can check if the websocket connected }); //This is a global reference to the websocket that we created. We need this because otherwise multiple JS //queries can't access the same WebSocket object. If each query had its own `new WebSocket()`, the interactivity of this //example wouldn't work, because they'd all be referring to different WebSocket connections. //This is what I was referring to when I mentioned that the two-way WebSocket example was "messier". //This global stuff isn't needed to simply listen on a WebSocket, as we'll see later with the Pusher-based 2nd example app. window.WEB_SOCKET = () => { return webSocket }; //This is our response message queue. I tried building this initially with a Temporary State object, but //I ran into some weird issues arouund live-updating that I suspect have something to do with React's internal visual cycles. let messages = []; //`window` properties in Retool must be functions to be able to access them as globals from within any query. //For example, when you see a line that looks like: //MESSAGES().push(...) it's really referring to our global response messages queue window.MESSAGES = () => { return messages; }; //I originally set this up as a simple `clear` parameter for the above function, but the global properties don't support function //arguments. I suspect this is some weird Javascript sandbox behavior, but either way, I can confirm that this works. window.CLEAR_MESSAGES = () => { messages = [] };