Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with function, firing click() multiple times

I have a problem with a project I'm doing; https://codepen.io/argestis/pen/gLraBq?editors=0001

I have a function, that is a simon says game. So far I want to push the values of the colors into an array and then compare that array into that function. Everything is working until i empty the value for the array i'm using to push the values that the user should enter from GIU, when i go back to the function GameOn() and i try to start pushing the values the click triggers multiple times.

Here's the reference function, but on console of the codepen I shared above you guys can see the error i'm getting.

function gameOn() {
    game.blue.on("click", function() {

        game.guessWhat.push(1);
        console.log("I were at blue")
        if (game.guessWhat.length !== game.count.length) {

        } else {
            verifySequence();
        }

    });

    game.red.on("click", function() {
        console.log("I were at red")
        game.guessWhat.push(2);
        if (game.guessWhat.length !== game.count.length) {

        } else {
            verifySequence();
        }
    });

    game.green.on("click", function() {
        console.log("I were at green")
        game.guessWhat.push(3);
        if (game.guessWhat.length !== game.count.length) {

        } else {
            verifySequence();
        }
    });

    game.yellow.on("click", function() {
        console.log("I were at yellow")
        game.guessWhat.push(4);
        if (game.guessWhat.length !== game.count.length) {

        } else {
            verifySequence();
        }


    });
}

Thank you for your time, guys!

like image 899
Alexandro Navarro Avatar asked Apr 29 '26 14:04

Alexandro Navarro


1 Answers

You register multiple 'click' event on the same item when calling verifySequence(). You can unregister click event prior to register it to solve that

//problem in verifySequence()
function verifySequence() {
...
  if (verify) {
    console.log("this is game.guessWhat: " + game.guessWhat);
    //when you call nextRound() you register click event on the same item (multiple times)
    nextRound();
  } else {
    clearUser();
  }
}
}


//making sure to unregister 'click' event before add one
game.blue.off("click").on("click", function() {
  ...
});

game.red.off("click").on("click", function() {
  ...
});

game.green.off("click").on("click", function() {
  ...
});

game.yellow.off("click").on("click", function() {
  ...
});
like image 159
RizkiDPrast Avatar answered May 01 '26 04:05

RizkiDPrast