I have a TypeScript class which looks something like this:
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);
}
}
Basically the code is supposed to register the _handleMouseMovement
event listener after the mouse has been locked to the canvas and and remove it once the lock has been removed.
The locking does work. It activates the position logging in _handleMouseMovement
but once I remove the lock via ESC
I do get the message Unlocked mouse pointer from canvas.
So _handleMouseMovement
is not removed and position logging continues.
I think that I did pay attention to not register anonymous functions, which might be the cause for a problem like this. So I wonder what else might be causing this behavior.
.bind
creates a new function. So your addition and removal are not for the same function.
Don't use .bind
and instead use arrow functions:
private _handleMouseMovement = (event: MouseEvent) => {
console.log('Mouse moved to: ', event.movementX, event.movementY);
}