How to handle addEventListener's click event in javascript

0

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

I created a game opening screen and after clicking play it goes to another screen. I called this event 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 you to a page where I choose the "phase" or "step" of the game I want to play, more or less like Candy Crush.

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

Is the section where I call the click event correct?

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

If not, how should I do it; Put multiple contexts and add the event in context? How would you do that?

    
asked by anonymous 03.06.2014 / 18:53

1 answer

1

One possible solution is to remove the listener after use, and add another one referring to the next state. This can be done within your checkClick 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 may 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 would be updated by a helper method with each navigation.

I'm not going to take your pleasure in programming this machine, it looks like fun! :)

    
03.06.2014 / 19:12