My TypeScript class is structured 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);
}
}
This code intends to handle the locking and unlocking of the mouse pointer on a canvas in TypeScript. However, upon removing the lock, the position logging in _handleMouseMovement
continues instead of being removed as expected.
I have tried to avoid using anonymous functions which could cause issues like this. I am now looking for other possible reasons behind this unexpected behavior.