Guillaume Marc
Guillaume Marc

Reputation: 161

Why can't I remove my event listener?

I have an issue with removeEventListener, it doesn't seem to work at all, I've seen some other questions on this site but I don't get it, can you help me?

displayImg() {
    console.log('img')
    for (var i = 1; i <= 4; i++) {
      var line = "l"+i;
      var position = 0;
      var addDivLine = document.createElement('div');
      addDivLine.className = 'line';
      addDivLine.id = line;
      document.getElementById('container').appendChild(addDivLine);
      for (var j = 1; j <= 7; j++) {
        var block = "b"+j;
        var element = line+"-"+block;
        var addDivBlock = document.createElement('div');
        addDivBlock.className = 'block';
        addDivBlock.id = element;
        document.getElementById(line).appendChild(addDivBlock);
        memory.addEvent(element);
      };
    };

showImage(event) {
        event.preventDefault();
        memory.clickedBlock++;
        var block = event.target.id;
        memory.removeEvent(block);
}


addEvent(id){
    document.getElementById(id).addEventListener('click', function(){memory.showImage(event)});
  },
  removeEvent(id){
    console.log("remove");
    document.getElementById(id).removeEventListener('click', function(){memory.showImage(event)});
  },

I am creating div elements then put an eventListener on them, I call the same function to remove the event, I use the same id, is there something that I forgot? I probably don't fully understand how it really works. Thanks a lot!

Upvotes: 1

Views: 254

Answers (2)

dfsq
dfsq

Reputation: 193261

In this two lines:

.addEventListener('click', function() { memory.showImage(event) });

and

.removeEventListener('click', function() { memory.showImage(event) });

function() { memory.showImage(event) } are two different functions. You need to provide reference to the same function in both cases in order to bind/unbind listener. Save it so some variable and use in both places:

.addEventListener('click', memory.showImage);
.removeEventListener('click', memory.showImage);

For example using directly memory.showImage will work properly as it's the same function in both cases.

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

The function looks like the same but its reference would be different. So, define the function in a scope where it's available for both function and use the reference in both case.

var callback =  function(){memory.showImage(event)};

addEvent(id){
    document.getElementById(id).addEventListener('click', callback);
}

removeEvent(id){
   console.log("remove");
   document.getElementById(id).removeEventListener('click', callback);
}

Upvotes: 1

Related Questions