gpt4 book ai didi

javascript - 为什么我在使用 removeEventListner 后不能添加 EventListener?

转载 作者:行者123 更新时间:2023-11-29 21:53:27 27 4
gpt4 key购买 nike

关于 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

最佳答案

原始代码有一些语法错误。既然你已经修复了这些,但显然代码不起作用,那么它必须在其他地方,以下工作:

<input id="demo">

<script>
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)); // adds listener on creation of Obj
}
}

function Obj(el) {
this.domOBJ = document.getElementById(el);
this.domOBJ.addEventListener("input", this, false);
}

Obj.prototype = {
handleEvent: function(){
console.log('input...');
}
},
selfDestruct: function() {
this.domOBJ.removeEventListener("input", this, false);
}
}

var obj = new OhYeah("demo"); // adds listener successfully

obj.removeStuff(); // removes listener successfully
obj.addStuff("demo") // adds listener successfully

</script>

这是一个jsfiddle显示它有效。

请注意,这是因为 Obj.prototypehandleEvent 属性。参见 W3C DOM 3 Events Specification, eventListener interface .

关于javascript - 为什么我在使用 removeEventListner 后不能添加 EventListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27793366/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com