Angular 2 document.removeEventListener在类中不起作用 [英] Angular 2 document.removeEventListener doesn't work in class

查看:69
本文介绍了Angular 2 document.removeEventListener在类中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动作结束后,我无法删除事件.我可以通过以下方式启动事件:

I can't remove event when action is end. I init event by click:

<span class="leftTopPoint" (click)="initResize($event)"></span>

export class SectionComponent {
    ...

    initResize(e): void {
        this.mouseX = e.clientX;
        this.mouseY = e.clientY;

        document.addEventListener('mousemove', this.onResize.bind(this), false);
        document.addEventListener('mouseup', this.stopResize.bind(this), false);
    }
}

我使用了 .bind(this),然后为此指针是可以的,但是当我调用stopResize()方法时,removeEventListener不起作用.方法onResize()仍然有效.

I used .bind(this) and then pointer this is okay, but when I call to method of stopResize(), removeEventListener doesn't work. Method onResize() still work.

export class SectionComponent { ...
    stopResize(e): void {
        document.removeEventListener('mousemove', this.onResize, false);
        document.removeEventListener('mouseup', this.stopResize, false);
    }
}

推荐答案

您必须为提供给 addEventListener 的 removeEventListener 指定与相同的功能.代码>. bind 返回的函数与原始函数不同(如果存在,则会出现 this 问题).

You have to specify the same function to removeEventListener as you provided to addEventListener. The function returned by bind is not the same as the original function (if it were, it would have the this issue).

因此,您必须存储绑定的函数,并在调用 removeEventListener 时使用它们.

So you'll have to store your bound functions and use them when calling removeEventListener.

initResize(e): void {
    this.mouseX = e.clientX;
    this.mouseY = e.clientY;

    if (!this.onResizeBound) {
        this.onResizeBound = this.onResize.bind(this);
    }
    if (!this.stopResizeBound) {
        this.stopResizeBound = this.stopResize.bind(this);
    }

    document.addEventListener('mousemove', this.onResizeBound, false);
    document.addEventListener('mouseup', this.stopResizeBound, false);
}

stopResize(e): void {
    document.removeEventListener('mousemove', this.onResizeBound, false);
    document.removeEventListener('mouseup', this.stopResizeBound, false);
}

这篇关于Angular 2 document.removeEventListener在类中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆