I am wanting my JavaScript object instances to handle their own events. so I have structured it like this.
class Player{
constructor(length=2)
{
this.length=length;
this.plHead = new PlayerHead(5,5,"#AA0000");
this.plBody = new PlayerBody(this.plHead.posX,this.plHead.posY, this.length);
this.plDir = "xAx";
this.plSpeed =0.25;
this.addEventListener("keydown",this.KeyPush);
}
//TEMPDATA JUST TO TEST IF THE IDEAR WORKS
PlMove(dir=0)
{
switch(dir)
{
case 0:
this.plHead.posX = this.plHead.posX +this.plSpeed;
break;
case 1:
this.plHead.posY = this.plHead.posY -this.plSpeed;
break;
case 2:
this.plHead.posX = this.plHead.posX -this.plSpeed;
break;
case 3:
this.plHead.posY = this.plHead.posY +this.plSpeed;
break;
}
}
//Player keypress
KeyPush(evt)
{
switch(evt.keyCode)
{
case 37:
this.PlMove(2);
break;
case 38:
document.getElementById("scoreDiv").innerHTML = this.title;
break;
case 39:
this.PlMove(0);
break;
case 40:
this.PlMove(3);
break;
}
}
}
however i was getting errors saying that this.PlMove is not a function. Then after further research i found out that the this. was referring to the DOM Document not the JavaScript class object even though it is inside the class.
So now I am trying to look for a way to put event listers on to an pure JavaScript object Not an DOM object even if i have to create my own events all though I have no clue how to do that either.