Richard Garfield Richard Garfield - 19 days ago 5
JSON Question

How to pass int via eventListener in Javascript?

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?

Answer

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) { ... }