Allison King
Allison King

Reputation: 13

javascript function using objects

I am designing a sort of game where there are team bases that surround a hexagonal board. The idea is that when a team base is clicked, it will be that team's turn. I have:

    $('.team').click(function(){
        var teamID=$(this).attr('id');
        explore(teamID);
    });

I then use the teamID to find the index of the team that was clicked, which is stored as an object from a json file with attributes such as teamname, score, etc.

    function explore(index){         // the game portion
        var turn=file[index];        // finds the team's info from json file
        $('.hex').click(function(){  // when a hex is clicked.... play the game
            alert(turn.teamname);       
            // game elements 
    }

This always works the first time around, however if I click on a different team box and then a hex, oftentimes it thinks that it is the turn of the box I clicked before. I added the alert(turn.teamname) to try to debug. If I'm clicking a different box, it will always alert the first box, and then send a second alert with the different box. I can't figure out why there would be two alerts? So it will always alert 'team1' and then 'team1','team2'. as I click more boxes it keeps alerting until it just alerts all of them. Additionally, if I have clicked more than two boxes before, even if I keep clicking the same hex it seems like it alternates between alerting me that it is 'team1' and 'team2'.

This is my first stackoverflow post so I hope it makes sense! Thanks!

Upvotes: -1

Views: 68

Answers (2)

Homer6
Homer6

Reputation: 15159

For something like this, I would recommend getting into meteor. The reactive programming model is much cleaner than an imperative one (especially in a game where it can quickly get complex).

I feel that this example illustrates what can be done very quickly using this framework (closest to your question's example).

To dive in, I'd recommend looking at the intro video, then proceed to the docs and a recent book about it.

Upvotes: 0

Ivancho
Ivancho

Reputation: 369

The reason you get this behavior is that you add event handlers to dom elements but never remove them. You need to change the way you handle clicks on the hexes. You may add an event handler once with http://api.jquery.com/one/ to the parent element that holds all hexes and check which hex is clicked inside the event handler. Or you can try a more trivial solution where you add an event listener once to the hexes and check if there is a selected team:

var turn;
var teamSelected = false;
function explore(index){         // the game portion
    teamSelected = true;
    turn=file[index];        // finds the team's info from json file
}
$('.hex').click(function(){  // when a hex is clicked.... play the game
    if (teamSelected) {
        alert(turn.teamname);       
        // game elements 
        teamSelected = false;
    }
}

Upvotes: 1

Related Questions