【发布时间】:2023-04-07 16:31:01
【问题描述】:
在mdn 我读到“一个 EventListener 在被删除后永远不能被调用”,但我认为这并不意味着你不能再次添加它(这没有意义)。这是我正在做的一个简化示例,所以如果示例中有一个小的语法错误,它可以被忽略(除非语法错误必须是问题)。
function OhYeah(el){
this.stuff = [];
this.stuff.push(new Obj(el));
}
OhYeah.prototype = {
removeStuff: function() {
for(var i = 0; i < this.stuff.length; i++){
this.stuff[i].selfDestruct(); // removes listener
}
this.stuff = [];
},
addStuff: function(el) {
this.stuff.push(new Obj(el)); // should add listener on creation of Obj
}
}
function Obj(el) {
// some other properties not shown that can be different even if the same "el" is used to create a new Obj
this.domOBJ = document.getElementById(el);
this.domOBJ.addEventListener("input", this, false);
}
Obj.prototype = {
...
handleEvent: function(){
...
},
selfDestruct: function() {
this.domOBJ.removeEventListener("input", this, false);
}
}
var obj = new OhYeah("demo"); // adds listener successfully
obj.removeStuff(); // removes listener successfully
obj.addStuff("demo") // you would think this would add the listener, BUT it does NOT
【问题讨论】:
-
.addEventListener("input", this -
@epascarello — 它之所以有效,是因为 Obj 在其原型上有一个 handleEvent 方法。处理程序将在处理事件时调用它,请参阅 W3C DOM 2 Events EventListener interface 的规范,在 DOM 3 Events spec 中更新。
-
MDN 不再说“…被删除后永远无法调用”。 ;-)
标签: javascript addeventlistener dom-events