JS / DOM : addEventListener / removeEventListener

If I add an EventListener to a DOM Element I am not able to remove this Listener.

class A
private fun myListener( event:Event )

fun xyz(element:Element)
// adds resize Event Listener to DOM Element element
element.addEventListener(“resize”,{ myListener(it) })

   // the remove does not work :-(
  element.removeEventListener("resize",{ myListener(it) })


the way how to add / remove the EventListener above does not work for remove. If I use an EventHandler Object for these methods it will work.

Am I totally wrong with my approach above ?


The expression { myListener(it) } creates a new object for the lambda, i.e. you end up having two separate objects.

You can store the lambda object in a global variable. Then you can add and remove that same object as an event listener.