Jump to content

creating multiple button problem


RyuMaster
 Share

Recommended Posts

Hi! I have several buttons in the loop, create like so:

 

for( var i = 0; i < 12; i++)
{
 
var card;
card = this.add.button(0, 0, "deck", this.selectCard, card, 0, 0, 0);
card.name = ""+i;
}
and this is function called on click:

 
selectCard:function()
{
alert(this.name);
 
}

 

 

 

 

The first 2 cards on table always alerts '0'; then it is fine - 1,2,3,4 e.t.c;

For some reason, the click event for card number 1 actually brings card number 0 object; Why?

 

 

Link to comment
Share on other sites

The problem is that when you use 'card' within the callback, you're referring to what card was previously, as until the end of the line card still refers to the previous card. Try it this way maybe:

// create an array to store all of the cardsvar cards = [];var card;for( var i = 0; i < 12; i++){  card = this.add.button(0, 0, "deck", function() { this.selectCard(i); }, this, 0, 0, 0);  card.name = "card_" + i;  // add the card to the array - i should be the same as the index at which it's added  cards.push(card);}this.selectCard = function(i) {  // retrieve the card by its index, logging the index and the card name to ensure they match  console.log(i, cards[i].name);}
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...