From aa408774699c02b50c3d7cab06f70a6af9c47f1e Mon Sep 17 00:00:00 2001 From: sthag Date: Sat, 4 Apr 2026 11:17:54 +0200 Subject: [PATCH] feat: Add a menu class to game Use event delegation and the data-action attribute. --- source/screens/demo/examples/game/tfw.liquid | 47 ++++++++++++++------ 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/source/screens/demo/examples/game/tfw.liquid b/source/screens/demo/examples/game/tfw.liquid index 8dfb6b6..983aaa6 100644 --- a/source/screens/demo/examples/game/tfw.liquid +++ b/source/screens/demo/examples/game/tfw.liquid @@ -113,25 +113,44 @@ tags: const menu = document.querySelector('body > header'); const placeholder = document.querySelectorAll('.background'); - menu.addEventListener('click', (event) => { - const buttons = menu.querySelectorAll('button'); - const buttonTarget = event.target.closest('button'); - - if (buttonTarget && event.button === 0) { - for (button of buttons) { - button.classList.remove('active'); - } - - buttonTarget.classList.add('active'); + class Menu { + constructor(element) { + // this._elem = element; + element.addEventListener('click', this.onClick.bind(this)); // Bind to get the clicked element and not the DOM element of the class } - }); + + escape() { + console.log('escape'); + } + + previous() { + console.log('previous'); + } + + quest() { + console.log('quest'); + } + + onClick(event) { + console.debug(event.target); + const action = event.target.dataset.action; + const siblings = event.target.parentElement.querySelectorAll('button'); + + if (action && event.button === 0) { + for (const sibling of siblings) { + sibling.classList.remove('active'); + } + + event.target.classList.add('active'); + this[action](); + } + }; + } placeholder.forEach(element => { const hue = randomIntFrom(0, 360); const grayscale = randomFloatFrom(0, 1); - console.log(hue, grayscale); - new RandomPixelCanvas(element, { width: Math.floor(element.parentElement.clientWidth), height: Math.floor(element.parentElement.clientHeight), @@ -139,5 +158,7 @@ tags: filter: 'grayscale(' + grayscale + ') hue-rotate(' + hue + 'deg)' }); }); + + new Menu(menu); {% endblock %} \ No newline at end of file