Sir
Sir

Reputation: 8280

removeEventListener not removing the listener

I have a event listener on my element which does not remove for some reason I don't know why.

I set it like this:

for (i = 0; i < data[0].length; i++) {
  (function(i){
    document.getElementById(i).addEventListener('click',
        function(){var self = this; begin(i,self,1);},false);})(i);                 
}

And the removal of the listener:

function begin(i,el,type){
    console.log('test');
    el.removeEventListener('click',function(){begin(i,el,type);},false);
}

But some reason the event listener is still assigned.... what am I not getting right here?

Upvotes: 1

Views: 98

Answers (1)

kavun
kavun

Reputation: 3381

You will need to retain reference to the event listener so that you can remove it. You can store it on the DOM element if you like.

for (var i = 0; i < data[0].length; i++) {
    (function(i){
        var el = document.getElementById(i);
        el['click-listener'] = function () { 
            var self = this;
            begin(i, self, 1);
        };
        el.addEventListener('click', el['click-listener'],false);
    })(i);                 
}

function begin(i, el, type) {
    el.removeEventListener('click', el['click-listener'], false);
}

Upvotes: 2

Related Questions