0

I have recently started to use createjs and have come to this problem (which doesnt have anything t odo with createjs):

for (a in ship.weapon) {

    //code
    button[a].addEventListener("click", function() {

        ship.weapon[a].amount = ship.weapon[a].amount.plus(1);
    });
    //code
}

The "a" variable will ofcourse at the time that the button is pressed be the lenght of the ship.weapon array. So how do i make it so that the "a" inside the click function will stay at the value of the for loop when it was made?

Vajura
  • 1,112
  • 7
  • 16

2 Answers2

3

You can use a closure to freeze the a value

for (a in ship.weapon) {

    (function(index) {
        button[index].addEventListener("click", function() {

            ship.weapon[index].amount = ship.weapon[index].amount.plus(1);
        });
    })(a); // calls the function I just defined passing 'a' as parameter
}
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
0

You must use a function for this, there is no other way.

function addEvent(a) {
   //code
   button[a].addEventListener("click", function() {
     ship.weapon[a].amount = ship.weapon[a].amount.plus(1);
   });
   //code
}

for (var a in ship.weapon) {
  addEvent(a);
}

This will work.

Liglo App
  • 3,719
  • 4
  • 30
  • 54