Reputation: 13
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++
Upvotes: 0
Views: 221
Reputation: 26
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
Upvotes: 1