Skip to content
Advertisement

How to pass “this” and another variable in EventListener?

I have a function in my addEventListener (#btn-1) that I want to remove eventually. I know that saving the function to a variable is the way to do it, but passing the “this” won’t work unless it’s wrapped in a function, which in turn won’t be able to be removed now because it’s either an anonymous function or it’s not a reference to the same function even if it’s named. Is there any way to do this?

const anonFunction = function(dis, str) {
  console.log(dis);
  console.log(str);
}

const myFn = function() {
  anonFunction(this, 'hello world');
}

document.querySelector('#btn-1').addEventListener('click', function() {
  anonFunction(this, 'hello world');
});

document.querySelector('#btn-2').addEventListener('click', function() {
  // doesn't work
  document.querySelector('#btn-1').removeEventListener('click', anonFunction);
});
<button id="btn-1" type="button">Call Function</button>
<button id="btn-2" type="button">Remove Event Listener</button>

UPDATE: SOLVED

Making another function calling the main function assigned to a variable and having that as the function to insert on adding and removing event listeners worked.

const anonFunction = function(dis, str) {
  console.log(dis);
  console.log(str);
}

const myFn = function() {
  anonFunction(this, 'hello world');
}

document.querySelector('#btn-1').addEventListener('click', myFn);

document.querySelector('#btn-2').addEventListener('click', function() {
  document.querySelector('#btn-1').removeEventListener('click', myFn);
});
<button id="btn-1" type="button">Call Function</button>
<button id="btn-2" type="button">Remove Event Listener</button>

Advertisement

Answer

Just name your function that uses this.

const anonFunction = function(dis, str) {
  console.log(dis);
  console.log(str);
}

const listener = function() {
  anonFunction(this, 'hello world');
};

document.querySelector('#btn-1').addEventListener('click', listener);

document.querySelector('#btn-2').addEventListener('click', function() {
  // doesn't work
  document.querySelector('#btn-1').removeEventListener('click', listener);
});
<button id="btn-1" type="button">Call Function</button>
<button id="btn-2" type="button">Remove Event Listener</button>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement