+ 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?

4th Jan 2019, 7:36 AM
Gordon
Gordon - avatar
7 odpowiedzi
+ 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);
4th Jan 2019, 9:52 AM
Pao
Pao - avatar
+ 3
Pao wow! genius~ Then, I can add the other back except the one I intend to remove
4th Jan 2019, 11:20 AM
Gordon
Gordon - avatar
4th Jan 2019, 4:06 PM
Gordon
Gordon - avatar
+ 2
Thank you for the question and answer, I learn a new stuff now 😊
4th Jan 2019, 10:13 AM
Calviղ
Calviղ - avatar
+ 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)
5th Jan 2019, 1:40 AM
Gordon
Gordon - avatar
+ 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" ; 😉
5th Jan 2019, 1:47 AM
Gordon
Gordon - avatar
+ 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
4th Jan 2019, 8:50 PM
오태경
오태경 - avatar