[英]How to remove an eventListener inside a class?
I have tried both of the following versions but I can't get the mousemove
eventListener to be removed.我已经尝试了以下两个版本,但我无法删除mousemove
eventListener。 I think my limited understanding of scoping inside of classes is causing some confusion, but I'd assume this should work.我认为我对类内部范围界定的有限理解造成了一些混乱,但我认为这应该可行。
export class Line extends Graphic {
constructor() {
super()
}
handleMouseMoveWhileDrawing(e) {
console.log(e);
}
stopDrawing() {
document.removeEventListener('mouseup', this.stopDrawing)
document.removeEventListener('mousemove', this.handleMouseMoveWhileDrawing)
}
startDrawing() {
document.addEventListener('mousemove', this.handleMouseMoveWhileDrawing)
document.addEventListener('mouseup', this.stopDrawing)
}
}
new Line().startDrawing()
export class Line extends Graphic {
constructor() {
super()
this.handleMouseMoveWhileDrawing = function(e) {
console.log(e);
}
}
stopDrawing() {
document.removeEventListener('mouseup', this.stopDrawing)
document.removeEventListener('mousemove', this.handleMouseMoveWhileDrawing)
}
startDrawing() {
document.addEventListener('mousemove', this.handleMouseMoveWhileDrawing)
document.addEventListener('mouseup', this.stopDrawing)
}
}
new Line().startDrawing()
Any help would be greatly appreciated.任何帮助将不胜感激。
@epascarello pushed me in the right direction. @epascarello 把我推向了正确的方向。
When passing a callback to an eventListener the this
parameter is automatically set to the DOM element that the eventListener is attached to.将回调传递给 eventListener 时, this
参数会自动设置为 eventListener 附加到的 DOM 元素。 Therefore this.handleMouseMoveWhileDrawing
inside the stopDrawing
method returned undefined
.因此this.handleMouseMoveWhileDrawing
方法中的stopDrawing
返回undefined
。
I was able to work around this by using .bind()
to override the this
in the stopDrawing
method:我可以通过使用.bind()
在stopDrawing
方法中覆盖this
来解决这个问题:
document.addEventListener('mouseup', this.stopDrawing.bind(this))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.