Is there any way to remove these type of eventlisteners...
No, not with addEventListener
/removeEventListener
. But you've tagged jquery, so keep reading, because you can with jQuery.
...or defining my3 function outside the event listener is the only way?
It's the only way with addEventListener
/removeEventListener
. You need to have a reference to the function that was added in order to remove it. So:
// Declare the function
function my3() {
alert(786);
}
// Add it
$("body")[0].addEventListener( "click", my3);
// Later, remove it
$("body")[0].removeEventListener( "click", my3);
You've tagged your question jquery, so I'll note that that isn't true of handlers attached with jQuery, because jQuery maintains its own list of event handlers rather than using the native DOM's list. That means you can remove all handlers for an event that were attached with jQuery from an element without having a reference to them, and/or use jQuery's "namespaced" events to remove just a subset of them, again without having to have references to them.
For instance:
$("body").on("click.foo", function my3() { alert(786); });
There, we've "namespaced" our click handler with foo
. Later, we can remove our handler without affecting any other click handlers:
$("body").off("click.foo");
Details in the documentation for on
and off
.