I have a class like this:
class Hanoi{
constructor(canvas) {
//construcor things
}
onMouseDown(e) {
for (var i = 0; i < this.pieces.length; i++) {
let piece = this.pieces[i];
if (piece.isClicked(e)) {
this.isDragging = true;
this.dragPiece = piece;
this.bound = evt => this.onMouseMove(evt);
this.canvas.addEventListener("mousemove", ev => {this.onMouseMove(ev)});
this.canvas.addEventListener("mouseup", ev =>{this.onMouseUp(ev)});
this.draw();
}
}
}
onMouseMove(e) {
this.dragPiece.x = e.clientX;
this.dragPiece.y = e.clientY;
this.draw();
}
onMouseUp(e) {
this.canvas.removeEventListener("mousemove", this.onMouseMove);
this.canvas.removeEventListener("mouseup", this.onMouseUp);
this.isDragging = false;
this.draw();
}
}
在onMouseDown中添加了两个事件监听器,但由于箭头函数的缘故,在调用onMouseUp时无法删除它们。
如何处理这种情况最好?
this.canvas.addEventListener("mouseup", this.onMouseUp);
?你基本上是使用一个已经有引用的普通函数,那么为什么要在其中插入箭头函数呢? - arbuthnottaddEventListener
将防止重复绑定,因为它们是相同的函数对象。 - spanky