Home > Net >  How do I change a variable inside a module pattern?
How do I change a variable inside a module pattern?

Time:08-17

I’m stuck on writing this module pattern for a tic tac toe game. When I click on a tile, it doesn’t increment gameBoard.tileCounter

const gameBoard = (() => {
    const tiles = document.querySelectorAll('.game-board > div')
    let tileCounter = 0;
    
    tiles.forEach(tile => tile.addEventListener('click', () => {
        tileCounter  ;
    }))
    
    return {tileCounter};
})();

If I do gameBoard.tileCounter it works, but shouldn’t I just be able to do tileCounter

CodePudding user response:

The idea of a module pattern is to access to the properties of that module instead of having a lot variables dangling, so in your scenario you can return a function to get the counter.

Something like this might work:

const gameBoard = (() => {
  const tiles = document.querySelectorAll(".game-board > div");
  let tileCounter = 0;

  tiles.forEach((tile) =>
    tile.addEventListener("click", () => {
      tileCounter  ;
    })
  );

  const getTileCount = () => tileCounter

  return { getTileCount };
})();

And by doing gameBoard.getTileCount() you will be able to get the actual count

CodePudding user response:

By doing return {tileCounter}; your returning a copy of tileCounter's value as a new object not a reference to the tileCounter property.

Change it like the following, so you're returning the instance not a copy of the value.

const gameBoard = (function() {
    const tiles = document.querySelectorAll('.game-board > div')
    this.tileCounter = 0;
    
    // for example sake
    setInterval(() => {
      this.tileCounter  ;
    }, 1000)
    
    return this;
})();

console.log(gameBoard.tileCounter)

setInterval(() => {
console.log(gameBoard.tileCounter)
}, 2000)

  • Related