issue in alpine.js in the course on laracast titled as alpine.js Essentials
i am covering the alpine.js course on laracast, the course title is alpine.js essentials where in first video we make a memory game but i am having a very weird issue and i can't solve it. so we have cards with each card having properties 1-flip, 2-clear, 3-color, and when two cards are clicked and match occurs they should be cleard(disappear) but that should take atleast one second so the color appears to be same, and for this we added setTimeout() function. but what happens is that after one second, the cleared cards again shows up which is weird and unexpected(and it don't happen if i remove the setTimeout()). so what i want to know is how the clear property changes with setTimeout(). here's the code.
<div x-data="game()" class="flex justify-center items-center min-h-screen px-4">
<h1 class="fixed top-0 right-0 font-bold text-3xl p-10">
<span x-text="points"></span>
<span class="text-xs">pts</span>
</h1>
<div class="flex-1 grid grid-cols-4 gap-6">
<template x-for="card in cards">
<div>
<button x-show="! card.cleared" :style="'background: '+ (card.flipped ? card.color : 'gray')"
class="w-full h-32" @click="flipCard(card)">
</button>
</div>
</template>
</div>
</div>
<script>
function game() {
return {
cards: [
{ color: 'green', flipped: false, cleared: false },
{ color: 'red', flipped: false, cleared: false },
{ color: 'blue', flipped: false, cleared: false },
{ color: 'yellow', flipped: false, cleared: false },
{ color: 'green', flipped: false, cleared: false },
{ color: 'red', flipped: false, cleared: false },
{ color: 'blue', flipped: false, cleared: false },
{ color: 'yellow', flipped: false, cleared: false }
],
get flippedCards() {
return this.cards.filter(card => card.flipped);
},
get clearedCards() {
return this.cards.filter(card => card.cleared);
},
get remainingCards() {
return this.cards.filter(card => !card.cleared)
},
get points() {
return this.clearedCards.length
},
flipCard(card) {
card.flipped = !card.flipped;
if (this.flippedCards.length === 2) {
if (this.hasMatch()) {
this.flippedCards.forEach(card => card.cleared = true);
setTimeout(() => {
this.flippedCards.forEach(card => card.flipped = false);
if (!this.remainingCards.length) {
alert('You Won');
}
}, 1000);
}
}
},
hasMatch() {
return this.flippedCards[0]['color'] === this.flippedCards[1]['color'];
}
}
}
</script>
Please or to participate in this conversation.