gpt4 book ai didi

javascript - 无法删除事件监听器 TypeScript/OOP JavaScript

转载 作者:行者123 更新时间:2023-11-30 09:53:10 26 4
gpt4 key购买 nike

onMouseUp 被触发,但它不会删除 EventListeners。我读过很多人们遇到麻烦的帖子,这是因为他们没有删除他们添加的相同功能,阅读 this我在想我可能有同样的问题,但我该如何处理呢?我不完全理解链接问题的答案。

class DragAndDrop {
item: Item;
documentBody: HTMLBodyElement;
constructor(documentBody: HTMLBodyElement, item: Item) {
this.documentBody = documentBody;
this.item = item;
this.documentBody.addEventListener("mousedown", this.onmousedown.bind(this));
}
onmousedown(event: MouseEvent): void {
if (CollisionDetector.pointInRect(event.clientX, event.clientY, this.item)) {
this.documentBody.addEventListener("mousemove", this.onMouseMove.bind(this));
this.documentBody.addEventListener("mouseup", this.onMouseUp.bind(this));
}
}
onMouseMove(event: MouseEvent): void {
this.item.x = event.clientX;
this.item.y = event.clientY;
}
onMouseUp(event: MouseEvent): void {
this.documentBody.removeEventListener("mousemove", this.onMouseMove.bind(this));
this.documentBody.removeEventListener("mouseup", this.onMouseUp.bind(this));
}
}

最佳答案

在您的代码中使用.bind

问题

  • .bind 创建函数的副本

foo.bind !== foo

解决方案

使用箭头函数。我为 mousedown 为你做的:

class DragAndDrop {
item: Item;
documentBody: HTMLBodyElement;
constructor(documentBody: HTMLBodyElement, item: Item) {
this.documentBody = documentBody;
this.item = item;
this.documentBody.addEventListener("mousedown", this.onmousedown);
}
onmousedown = (event: MouseEvent): void => {
if (CollisionDetector.pointInRect(event.clientX, event.clientY, this.item)) {
// Similarly ...
}
}
}

更多

关于箭头函数的更多信息:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

关于javascript - 无法删除事件监听器 TypeScript/OOP JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35282111/

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