我一定忽略了一些事情,因为事件侦听器没有被删除。我创造了一个小复制品。我没有使用任何正常的函数。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();
发布于 2020-01-06 16:40:04
问题是,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();
https://stackoverflow.com/questions/59615500
复制相似问题