【发布时间】:2017-11-10 04:29:28
【问题描述】:
我希望我的 JavaScript 对象实例能够处理它们自己的事件。所以我把它组织成这样。
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;
}
}
}
但是我收到错误说 this.PlMove 不是一个函数。 然后经过进一步的研究,我发现这个。指的是 DOM 文档而不是 JavaScript 类对象,即使它在类内部。
所以现在我正在尝试寻找一种将事件列表器放在纯 JavaScript 对象而不是 DOM 对象上的方法 即使我必须创建自己的事件,尽管我也不知道该怎么做。
【问题讨论】:
-
addEventListener适用于 DOM 对象。如果你想处理普通对象上的事件,你应该考虑其他事件机制,比如npmjs.com/package/event-emitter。这个问题可能与stackoverflow.com/questions/20835768/… 重复 -
你给我的链接使用了 npm。代码会在没有 node.js 的计算机上运行吗?
标签: javascript class events keypress