javascript - 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();
解决方案
问题是this
insideOnAdd
没有绑定到实例。
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();
推荐阅读
- environment-variables - 如何将环境变量传递给 Jboss 上的 Angular App
- php - Htaccess 重定向不起作用从子子文件夹到根文件
- c# - 按角色或细粒度权限过滤 DTO
- r - R 中的 rvest webscrape
- python - 识别 input_string 中的唯一字母和相应计数
- jupyter-notebook - 在侧边栏中设置自定义插件默认打开 - Jupyterlab
- scala - Spark 作业状态记录
- c - 读取未初始化的整数时出现不可预测的行为
- ios - iOS 12 通知扩展自定义 UI 未捕获 UIButton 点击
- javascript - 带有jquery函数问题的循环打印Java脚本