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

时间:2015-01-06 06:36:54

标签: javascript addeventlistener dom-events

On 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

1 个答案:

答案 0 :(得分:2)

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

<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.prototype handleEvent 属性。请参阅W3C DOM 3 Events Specification, eventListener interface