class Tictactoe_Client { game_id = 0; // TODO set when joining game /** * Fetches the game state, updates the UI, and installs click handlers. */ async init() { let i = 0; for (const button of this.view.grid.getElementsByTagName("button")) { const cell = i; button.addEventListener('click', () => { this.handleJsonUrl(`/set/${this.game_id}/${cell}`); }); i++; } } /** * Fetches the given URL and updates the internal state from the parsed JSON. * * Keeps polling for updates if the updated state could change remotely. * * @param {string} url the URL to fetch that will return tictactoe JSON. */ async handleJsonUrl(url) { let response = await fetch(url); if (!response.ok) { let error = await response.text(); console.log("Error: " + error); return; } const json = await response.json(); this.updateHtml(json); } /** Update the HTML based on JSON game state. */ updateHtml(json) { let i = 0; for (const button of this.grid.getElementsByTagName("button")) { const cellText = json.grid[i]; // Set the data-state attribute which drives CSS formatting. button.setAttribute('data-state', cellText); // Set the text contents of the cell. button.textContent = cellText; i++; } } }