Skip to content Skip to sidebar Skip to footer

Javascript: Can't Handle Events For Multiple Instances

I have put together a fun API for game creation. In the code I create a prototype for Mover and then extend it with several specific prototypes (Gold, Monster, and Hero). Each one

Solution 1:

So I debug your code and I found the cause of your problem. The problem was when you create a new instance of monster you storing a reference to it on the monster var. And when you delete it you don't delete / update the reference to it. So your delete function myField.DeleteMover(id) try to delete a monster already deleted. How to solve this.

// create an array to keep ref to our instancesvar monsters= [];
// var monster = null;function addMonster()
{
  // monster = goldField.AddMonster();⏎// push every monster in array
  monsters.push(goldField.AddMonster());
}

function killMonster()
{
  // if array.length is trueif (monsters.length) {
    // call the destroy function on the last ref
    monsters[monsters.length - 1].Destroy();
    // remove the last ref from array using pop
    monsters.pop();
  }
//monster.Destroy();
}

This is working however I think all of this should be done in the objects itself. And you should not care about it here.

Another advice try to use more array methods. Avoid using delete on array index because it mess with index and count instead use splice(index, 1) same for add item in array use push instead of arbitrary index.

Anyway funny game! Good luck to finish it.

Edit, after your answer I go back an test. To make it work I do this.

// First go inGoldField.prototype.DeleteMover and replace the ugly delete index bythis.movers.splice(id, 1);
// Then in the Mover.prototype.Destroy// This part is a a little blurred for me.// the current HTMLtag looks good but when I console.log like this
console.log('before', this.HTMLtag);
this.HTMLtag = document.querySelector("#mover" + this.myID);
console.log('after', this.HTMLtag);
// They are not equal look like the first is outdated

You should convert all your delete and add to splice and push methods. This is just a quick debug I don't know why the selector is outdated.

Solution 2:

So I check the code again and I make it work without refreshing the selector. The problem is caused by the creation of dom element with innerHTML.

First reset

this.HTMLtag.src=this.destroyURL

Then instead of

//Mover.prototype.Destroythis.tag.innerHTML+="<img id='mover"+this.moverCount+"'>";

I create a img dom el.

var img = document.createElement("img");
img.setAttribute('id', 'mover' + this.moverCount);
this.tag.appendChild(img);

All Monsters are now deleted with the image. I don't check for the hero but first you should update your innerHTML and reply if there is still a problem. I don't think there is any problem with some prototype.

Post a Comment for "Javascript: Can't Handle Events For Multiple Instances"