美文网首页我爱编程
angular2 清除document事件绑定

angular2 清除document事件绑定

作者: webmrxu | 来源:发表于2018-03-20 12:09 被阅读0次

参考文章:Remove or destroy event listener

使用angular2 有时候万不得已需要使用原生的事件绑定,例如使用window, document 绑定全局事件,但这样往往会很耗性能,还存在事件叠加的可能,因此需要取消事件绑定,使用原生的取消事件接口。

绑定事件代码如下:

   // 移动端开始滑动
  document.addEventListener('touchstart',this.headeTouchStart.bind(this), false);

现在在angular 的 ngOnDestroy 生命周期中取消事件的绑定,但是没有生效。

取消绑定事件如下:

ngOnDestroy(){
    document.removeEventListener('touchstart',this.headeTouchStart.bind(this), false)
 
  }

stackoverflow问题解决方式

解决步骤: 在绑定事件时,不使用bind 绑定this, 绕个弯绑定this (???黑人脸)

绑定事件代码如下:

    // 移动端开始滑动
    this.headeTouchStart = this.headeTouchStart.bind(this);
    document.addEventListener('touchstart',this.headeTouchStart, false);

在ng组件销毁的生命周期函数中取消事件绑定:

ngOnDestroy(){
    document.removeEventListener('touchstart',this.headeTouchStart, false)
  }

相关文章

网友评论

    本文标题:angular2 清除document事件绑定

    本文链接:https://www.haomeiwen.com/subject/vsvvqftx.html