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?
JavaScript
x
17
17
1
const anonFunction = function(dis, str) {
2
console.log(dis);
3
console.log(str);
4
}
5
6
const myFn = function() {
7
anonFunction(this, 'hello world');
8
}
9
10
document.querySelector('#btn-1').addEventListener('click', function() {
11
anonFunction(this, 'hello world');
12
});
13
14
document.querySelector('#btn-2').addEventListener('click', function() {
15
// doesn't work
16
document.querySelector('#btn-1').removeEventListener('click', anonFunction);
17
});
JavaScript
1
2
1
<button id="btn-1" type="button">Call Function</button>
2
<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.
JavaScript
1
14
14
1
const anonFunction = function(dis, str) {
2
console.log(dis);
3
console.log(str);
4
}
5
6
const myFn = function() {
7
anonFunction(this, 'hello world');
8
}
9
10
document.querySelector('#btn-1').addEventListener('click', myFn);
11
12
document.querySelector('#btn-2').addEventListener('click', function() {
13
document.querySelector('#btn-1').removeEventListener('click', myFn);
14
});
JavaScript
1
2
1
<button id="btn-1" type="button">Call Function</button>
2
<button id="btn-2" type="button">Remove Event Listener</button>
Advertisement
Answer
Just name your function that uses this
.
JavaScript
1
15
15
1
const anonFunction = function(dis, str) {
2
console.log(dis);
3
console.log(str);
4
}
5
6
const listener = function() {
7
anonFunction(this, 'hello world');
8
};
9
10
document.querySelector('#btn-1').addEventListener('click', listener);
11
12
document.querySelector('#btn-2').addEventListener('click', function() {
13
// doesn't work
14
document.querySelector('#btn-1').removeEventListener('click', listener);
15
});
JavaScript
1
2
1
<button id="btn-1" type="button">Call Function</button>
2
<button id="btn-2" type="button">Remove Event Listener</button>