0

I am trying to get a userRound function for a game of battleship to await the selection of a grid cell/coordinate by calling a function that listens for the change of value of a property within an object. I've been trying to do this by using a setter function on a proxy of the object to return a promise to the listening function that would then hopefully resolve when the value is set. I was using this answer as a steer: Listening for variable changes in JavaScript

The value of the object is set when an eventlistener on the grid cells picks up a click event. That eventlistener is set within a different module (ui.js) to the one that houses the userRound function (game.js). I've imported the object that i'm writing the coordinate value to to the game.js module so that the eventlistener handler function can access it. The best i'm able to achieve at the moment is writing the coordinate value to the console log but i can't work out how to move the value over to the context of the userRound function in a separate module to then use to proceed with that turn of the game. Here is the code from the game.js module:


let userAttackCoords = {coords:null};

let proxyAttackCoords;

async function userRound() {

    deactivateElement(playerArea);   
    activateElement(compArea);

    const coords =  await listenForCoordSelection();

    console.log(coords) // produces undefined //

    function listenForCoordSelection() {
        return proxyAttackCoords = new Proxy(userAttackCoords, {
            set: function (target, key, value) {
                console.log(`${key} set to ${value}`);
                target[key] = value;              
                return new Promise(res, rej => {
                    res(target[key]);
                });
            }
        });
    }
}

And the code from the ui.js module:

function prepareCompBoard() {
    const cells = compBoard.querySelectorAll('.grid-cell');
    cells.forEach(cell => {
        cell.addEventListener('click', () => {
            proxyAttackCoords.coords = cell.dataset.xy;
        }, {once:true});
    });
}

I know that I could just use the eventlisteners already assigned to the grid cells to trigger the continuation of the code but i was hoping to do it this way so that everything could be housed under the userRound function and i wouldn't have to do any DOM interaction within the game.js module.

Bkidji
  • 1

0 Answers0