This question already has answers here:
The value of “this” within the handler using addEventListener
                                
                                    (8个答案)
                                
                        
                                2天前关闭。
            
                    
由于我的事件监听器未删除,因此我必须忽略某些内容。我制作了一个小复制品。我没有使用任何函数。 addEventListener的签名与removeEventListener相同。调度事件时,仍然会触发我的侦听器。

尽管第3个参数在任何现代浏览器中都不是默认值,但我仍然出于调试目的添加了该参数,但没有任何区别。

有人可以在这里帮我吗。我想念什么?



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();

最佳答案

问题是this中的OnAdd没有绑定到实例。



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();

关于javascript - removeEventListener未删除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59615500/

10-09 20:19