0

I generate a list of Magic cards from a Json file.

for (i in set.cards) {
        leftCardElement = document.createElement("p");
        leftCardElement.innerHTML = set.cards[i].points + " " + set.cards[i].name + "&nbsp";
        leftCardElement.addEventListener("click", leftCardClicked);
}

 function leftCardClicked(event) {// access card.cost and other things }

The problem is that when the leftCardElementClicked() method is called I'd like to be able to have access to the set.cards[i] object. The this object seems to refer to the element that I clicked on inside of leftCardElementClicked(). Is there some way that I can pass the index i to the event handler so I can get my card object?

Richard Garfield
  • 455
  • 1
  • 5
  • 13

3 Answers3

1

Same like @AlejandroC but without the dependency on the i (this i will change on each iteration) , therefore I clone it before passing, using with Object.assign()

In your for loop do:

leftCardElement.addEventListener("click", leftCardClicked.bind(this, Object.assign({},set.cards[i]));

then your function should be:

function leftCardClicked(card, event) { ... }
URL87
  • 10,667
  • 35
  • 107
  • 174
0

In your for loop do:

leftCardElement.addEventListener("click", leftCardClicked.bind(this, set.cards[i]);

then your function should be:

function leftCardClicked(card, event) { ... }
Alejandro C.
  • 3,771
  • 15
  • 18
-1

Instead of attaching leftCardClicked directly as your event handler, instead use an anonymous function:

leftCardElement.addEventListener("click", function(evt) {
  leftCardClicked(evt,i);
});

where i is your loop index. This creates a closure that passes that value of i to that instance of the click handler.

Ryan
  • 91
  • 5