From 30cbc40d38dee1e45be3cecaaa65708566086e72 Mon Sep 17 00:00:00 2001 From: Manuel Thalmann Date: Thu, 15 Dec 2022 14:17:11 +0100 Subject: [PATCH] Move all click handlers to the `App` --- src/js/Components.js | 84 ++++++++++++++++++++++++-------------------- 1 file changed, 45 insertions(+), 39 deletions(-) diff --git a/src/js/Components.js b/src/js/Components.js index e89db15..b0d5691 100644 --- a/src/js/Components.js +++ b/src/js/Components.js @@ -1,6 +1,9 @@ import { Constants } from "./Constants.js"; const saveGameKey = "connect-force-save"; +const newGameClass = "new-game"; +const saveGameClass = "save-game"; +const loadGameClass = "load-game"; /** * Gets a component which represents the specified {@link game `game`}. @@ -20,20 +23,35 @@ export function App(game) { let target = /** @type {HTMLElement} */ (event.target); - for (let y = 0; y < game.board.length; y++) + if (target.classList.contains(newGameClass)) { - let rowLength = game.board[y].length; - - for (let x = 0; x < rowLength; x++) + game.reset(); + } + else if (target.classList.contains(saveGameClass)) + { + localStorage.setItem(saveGameKey, JSON.stringify(game.dump())); + } + else if (target.classList.contains(loadGameClass)) + { + game.load(JSON.parse(localStorage.getItem(saveGameKey))); + } + else + { + for (let y = 0; y < game.board.length; y++) { - let node = document.querySelector(".board").children.item(y * rowLength + x); + let rowLength = game.board[y].length; - if (node === target || node.contains(target)) + for (let x = 0; x < rowLength; x++) { - if (game.addChip(x, y)) + let node = document.querySelector(".board").children.item(y * rowLength + x); + + if (node === target || node.contains(target)) { - game.state.turnCount++; - game.draw(); + if (game.addChip(x, y)) + { + game.state.turnCount++; + game.draw(); + } } } } @@ -123,41 +141,30 @@ export function MenuBar(game) { className: "menu-bar" }, [ Button, - { - text: "New Game", - attributes: { - onclick: () => - { - game.reset(); - } + [ + "New Game", + { + className: newGameClass } - } + ] ], [ Button, - { - text: "Save Game", - attributes: { - onclick: () => - { - localStorage.setItem( - saveGameKey, - JSON.stringify(game.dump())); - } + [ + "Save Game", + { + className: saveGameClass } - } + ] ], [ Button, - { - text: "Load Game", - attributes: { - onclick: () => - { - game.load(JSON.parse(localStorage.getItem(saveGameKey))); - } + [ + "Load Game", + { + className: loadGameClass } - } + ] ] ]; } @@ -165,17 +172,16 @@ export function MenuBar(game) /** * Renders a button. * - * @param {{text: string, attributes: (Partial & Record)}} data + * @param {...ElementDescriptor[1][]} content * The settings of the button. * * @returns {NodeDescriptor} * The rendered element. */ -export function Button(data) +export function Button(content) { return [ "button", - data.attributes, - data.text + ...content ]; }