首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >removeEventListener未移除

removeEventListener未移除
EN

Stack Overflow用户
提问于 2020-01-06 16:19:49
回答 1查看 73关注 0票数 1

我一定忽略了一些事情,因为事件侦听器没有被删除。我创造了一个小复制品。我没有使用任何正常的函数。addEventListener的签名与removeEventListener完全相同。不过,当我发送事件时,我的侦听器仍然被触发。

尽管第三个参数在任何现代浏览器中都不是默认的,但我仍然为调试目的添加了它,但是它并没有产生任何影响。

有人能帮帮我吗。我遗漏了什么?

代码语言:javascript
复制
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();

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-06 16:40:04

问题是,this内部的OnAdd没有绑定到实例。

代码语言:javascript
复制
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

代码语言:javascript
复制
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();

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59615500

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档