Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading