gpt4 book ai didi

javascript - 来自箭头函数的 ES6 removeEventListener (OOP)

转载 作者:行者123 更新时间:2023-11-29 11:01:38 26 4
gpt4 key购买 nike

<分区>

我有这样一个类:

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 时删除它们。

处理这个问题的最佳方法是什么?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com