How to handle addEventListener click event in javascript

I need to develop a game using HTML 5 and Javascript with the game being inside a canvas.

I created a game opening screen and after I click on play it directs to another screen. I called this way the click

document.getElementById('canvas').addEventListener('click', verificaClick, false);

Where canvas is the id of my canvas and verificaClick the function that sends to the next step according to the selected option because I have the options "play", "how to play" and "credits".

If I click play it directs to a page where I choose the "stage " or" stage " of the game I want to play, more or less like Candy Crush.

My problem is that canvas redraws everything right, however remains the click event of the first part of the game, the first canvas drawing. I'm redrawing, erasing the context and redrawing, but it remains the same click on the positions of the first "buttons" I drew.

Is the snippet where I call the click event correct?

document.getElementById('canvas').addEventListener('click', verificaClick, false);

If not, like me should I do; put multiple contexts and add the event in context? How would you do that?

Author: Bruno Augusto, 2014-06-03

1 answers

One possible solution is to remove the listener after use, and add another referring to the next state. This can be done within your verificaClick function, after you validate that the click was actually on the button to the next screen.

function verificaClick(){
    // ...

    // Não sei exatamente como você faz a validação, mas vamos supor
    // que a condição abaixo verifique o clique sobre o botão 'Jogar':
    if(x > 100 && x < 300 && y > 350 && y < 410){
        // ...
        document.getElementById('canvas').removeEventListener('click', verificaClick, false);
        document.getElementById('canvas').addEventListener('click', verificaClickLevelSelect, false);
        // ...
    }

    // ...
}

function verificaClickLevelSelect(){
    // ...

    // Caso seja detectado um clique no botão 'Voltar', por exemplo:
    if(x > 50 && x < 150 && y > 50 && y < 90){
        // ...
        document.getElementById('canvas').removeEventListener('click', verificaClickLevelSelect, false);
        document.getElementById('canvas').addEventListener('click', verificaClick, false);
        // ...
    }

    // ...
}

Of course, your navigation tree can be huge. In this case, this method can be too rudimentary and difficult to maintain. A more elaborate implementation could include "Automatic" Maintenance of listeners through an object in the global scope, which would store the state machine and be updated by a helper method with each navigation.

I won't take your pleasure in programming this machine, it sounds fun! :)

 1
Author: Rui Pimentel, 2014-06-03 17:12:36