无法删除EventListener

时间:2018-05-18 18:49:25

标签: typescript pointerlock

我有一个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不会被删除,并且位置记录会继续。

我认为我确实注意不注册匿名函数,这可能是造成类似问题的原因。所以我想知道还有什么可能导致这种行为。

1 个答案:

答案 0 :(得分:7)

.bind创建功能。因此,您的添加和删除不适用于相同的功能。

修复

https://www.atlaspm.com/toms-tutorials-for-excel/而是使用箭头功能:

private _handleMouseMovement = (event: MouseEvent) => {
    console.log('Mouse moved to: ', event.movementX, event.movementY);
}