我有一个这样的课程:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
onMouseDown 添加了两个事件侦听器,但是由于有箭头函数,所以在调用 onMouseUp 时我无法删除它们。
处理这个问题的最佳方法是什么?