我有一个 TypeScript 类,它看起来像这样:
class MyClass {
let canvas: any;
constructor(canvas: any) {
this.canvas = canvas;
this.canvas.requestPointerLock = this.canvas.requestPointerLock;
document.exitPointerLock = document.exitPointerLock;
this.canvas.onclick = this._mouseClickHandler.bind(this);
document.addEventListener('pointerlockchange', this._togglePointerLock.bind(this), false);
}
private _mouseClickHandler(event: MouseEvent): void {
this.canvas.requestPointerLock();
}
private _togglePointerLock() {
if (document.pointerLockElement === this.canvas) {
console.info('Locked mouse pointer to canvas.');
document.addEventListener('mousemove', this._handleMouseMovement.bind(this), false);
} else {
console.info('Unlocked mouse pointer from canvas.');
// THIS DOES NOT WORK
document.removeEventListener('mousemove', this._handleMouseMovement.bind(this), false);
}
}
private _handleMouseMovement(event: MouseEvent) {
console.log('Mouse moved to: ', event.movementX, event.movementY);
}
}
基本上,代码应该_handleMouseMovement
在鼠标锁定到画布后注册事件侦听器,并在锁定被移除后将其移除。
锁定确实有效。它激活了位置记录,_handleMouseMovement
但是一旦我通过删除锁定,ESC
我确实收到消息Unlocked mouse pointer from canvas.
所以_handleMouseMovement
没有删除并且位置记录继续。
我认为我确实注意不要注册匿名函数,这可能是导致此类问题的原因。所以我想知道还有什么可能导致这种行为。