+ 5
{SOLVED} Only Named Function can be removed with removeEventListener()?
My test: https://code.sololearn.com/Wh2LnQmYHmuk/?ref=app Reason: I answered an Q&A and said this is not working. I was not wrong. I know named function can be removed. But, is there anyway to remove anonymous function from click event listener?
7 Antworten
+ 22
Yes, you’re correct, only named functions can be removed with removeEventListener() because it needs a reference to the function object. Details here: https://dev.to/em4nl/function-identity-in-javascript-or-how-to-remove-event-listeners-properly-1ll3
The only way I can think of removing an event listener with an anonymous callback function is by cloning the element node and replacing the original node with the clone, although that would remove ALL of its event listeners.
var clone = btn1.cloneNode(true);
btn1.parentNode.replaceChild(clone, btn1);
+ 3
Pao wow! genius~
Then, I can add the other back except the one I intend to remove
+ 3
I tested it, really works~
https://code.sololearn.com/W6NpiFj2L4kt/?ref=app
+ 2
Thank you for the question and answer, I learn a new stuff now 😊
+ 2
오태경 you are right,
Remove 1 is to remove btn1, which was removed on first press, so starting from second press, the Remove 1 will return error because btn1 no longer exists. 😉
The test is for testing in this sequence:
Green -> Red -> Remove 1 -> Green (show successful removal of green color)
+ 2
오태경
if you want to treat it as an error and debug it,
In strongRemoveEventListener(),
add
btn3.removeEventListener("click",strongRemoveEventListener);
and if you want to include display, add one more
btn3.innerText = "Removed" ;
😉
+ 1
Another Question.
Just found one Error.
Totally Captured picture. But i Couldn't Posted in this Comment. At least Tried it with {Remove 1}.
[Cannot Read Property of 'ReturnChild' of Null.] when we 'Taps' of {Remove 1} button.
https://code.sololearn.com/W6NpiFj2L4kt/?ref=app