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

Why can't I addEventListener after removeEventListner has been used?

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 显示它有效。

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