首页 > 解决方案 > removeEventListener 未删除

问题描述

我必须忽略某些东西,因为我的事件监听器没有被删除。我创建了一个小型复制品。我没有使用任何功能。addEventListener 的签名与 removeEventListener 相同。当我发送事件时,我的监听器仍然被触发。

即使第三个参数在任何现代浏览器中都不是默认的,我仍然添加它以进行调试,但它没有任何区别。

有人可以帮我吗?我错过了什么?

function Foo(){
    this.AddComponent();
}

Foo.prototype.AddComponent = function(){
    var self = this;
    
    window.addEventListener("OnAdd",self.OnAdd,false);

    var ev = new CustomEvent('OnAdd', {
        detail: {}
    });

    window.setTimeout(function(){
      console.log('dispatched');
      window.dispatchEvent(ev)
    },1000);
}

Foo.prototype.OnAdd = function(event){
    console.log('I was fired!');

    var self = this;    
    window.removeEventListener("OnAdd",self.OnAdd,false);

    // try to fire again, which in theory should not work
    var ev = new CustomEvent('OnAdd', {
        detail: {}
    });
    
    window.dispatchEvent(ev);
}

new Foo();

标签: javascript

解决方案


问题是thisinsideOnAdd没有绑定到实例。

function Foo(){
    this.OnAdd = this.OnAdd.bind(this);
    this.AddComponent();
}

Foo.prototype.AddComponent = function(){
    var self = this;
    
    window.addEventListener("OnAdd",self.OnAdd,false);

    var ev = new CustomEvent('OnAdd', {
        detail: {}
    });

    window.setTimeout(function(){
      console.log('dispatched');
      window.dispatchEvent(ev)
    },1000);
}

Foo.prototype.OnAdd = function(event){
    console.log('I was fired!');

    var self = this;    
    window.removeEventListener("OnAdd",self.OnAdd,false);

    // try to fire again, which in theory should not work
    var ev = new CustomEvent('OnAdd', {
        detail: {}
    });
    
    window.dispatchEvent(ev);
}

new Foo();

相同的代码,就像 ES6 一样class

class Foo {
  constructor() {
    this.OnAdd = this.OnAdd.bind(this);
    this.AddComponent();
  }
  AddComponent() {
    var self = this;

    window.addEventListener("OnAdd", self.OnAdd, false);

    var ev = new CustomEvent('OnAdd', {
      detail: {}
    });

    window.setTimeout(function() {
      console.log('dispatched');
      window.dispatchEvent(ev)
    }, 1000);
  }
  OnAdd(event) {
    console.log('I was fired!');

    var self = this;
    window.removeEventListener("OnAdd", self.OnAdd, false);

    // try to fire again, which in theory should not work
    var ev = new CustomEvent('OnAdd', {
      detail: {}
    });

    window.dispatchEvent(ev);
  }

}

new Foo();


推荐阅读