0

I ran into an issue when using addEventListener inside of array. My goal is to reduce "enemy" hp after each click. Adding a bit of code for explanation:

var image;
var enemy = [];

function start()
{
  image = document.getElementById("image");
  
  enemy.push(new createEnemy());
  
  draw()
}

function draw()
{
  if(enemy[0].hp <= 0)  enemy.splice(0 , 1);  /*Also, will my splice work 
if instead of enemy[0] a "for loop" with (if(enemy[i].hp <= 0) enemy.splice(i, 1);) 
was used?*/

  requestAnimationFrame(draw);
}

function createEnemy()
{
  this.hp = 2;  //Value to be decreased
  this.image = document.getElementById("image");
  this.image.addEventListener("click", function()
    {
      console.log("Click works but hp doesn't decrease");
      this.hp--; //Problem cause
    })
}
<!DOCTYPE html>
<html>
  <body onload="start()">
    <img id="image" src="https://i.imgur.com/hZWobCv.gif">
  </body>
</html>

Also, is there a more simple way to destroy an "enemy" if their hp reaches 0 than using splice in animation frame?

1 Answers1

1

the callback function has its own this, use an arrow function instaed :

this.image.addEventListener("click", () =>
    {
      console.log("Click works but hp doesn't decrease");
      this.hp--; // will use the parent's this.hp
    })

var image;
var enemy = [];

function start() {
  image = document.getElementById("image");

  enemy.push(new createEnemy());

  draw()
}

function draw() {
  if (enemy[0].hp <= 0) enemy.splice(0, 1); //Also, will my splice work if instead of enemy[0] a "for loop" with (enemy[i], enemy.splice(i, 1);) was used?

  requestAnimationFrame(draw);
}

function createEnemy() {
  this.hp = 10; //Value to be decreased
  this.image = document.getElementById("image");
  this.image.addEventListener("click", () => {
    console.log("Click works , this.hp = ", this.hp);
    this.hp--; 
  })
}
<!DOCTYPE html>
<html>

<body onload="start()">
  <img id="image" src="https://i.imgur.com/hZWobCv.gif">
</body>

</html>
Taki
  • 17,320
  • 4
  • 26
  • 47
  • Thanks, that part worked. But now I have another issue, why splice (in line 13) doesn't remove created by createEnemy() function in HTML DOM? What different approach should I take to remove both values saved inside of enemy[] array and from HTML DOM? – Gytis Dokšas Feb 21 '19 at 22:15