Delete event listener if I only know the element and event

Is there a way to remove an event listener if I only know the element and event, but don’t know which function?

Sort of:

var foo = getElementById("foo");
foo.removeEventListener('click');
+4
source share
2 answers

JS clean methods

It is not possible to disconnect an event listener without reference to its listener method.

A method definition requires you to specify listener.

JS with modifications

You can use some custom functions:

function addEventListenerAndRemember(element, type, listener, useCapture)
{
    if (!element.myEvents) element.myEvents = {};
    if (!element.myEvents[type]) element.myEvents[type] = [];

    element.myEvents[type].push(listener);

    element.addEventListener(type, listener, useCapture || false);
}

function removeAllEventListener(element, type)
{
    element.myEvents.forEach(function() {
        element.myEvents[type].forEach(function(listener) {
            element.removeEventListener(type, listener);
        });
        element.myEvents[type] = [];
    });
}

I'm not sure if this code works - this is just an example of demonstrating an idea.
You can also wrap these methods in addEventListenerand override the default behavior. As well as:

Element.prototype.addEventListenerBase = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(type, listener, useCapture) {
    // do the same
};

JQuery Method

, jQuery .

:

$("#foo").on('click', function() {

});

:

$("#foo").off('click');
+3

.. , ..

<a href="#" id="mydiv">click</a>
<a href="#" onclick="removeHandler()">remove</a>

<script>
document.getElementById("mydiv").addEventListener("click", myFunction);

function myFunction() {
    alert('hello');
}

function removeHandler() {
    document.getElementById("mydiv").removeEventListener("click", myFunction);
}
</script>

, .

var el = document.getElementById('mydiv'),
elClone = el.cloneNode(true);

el.parentNode.replaceChild(elClone, el);
0

Source: https://habr.com/ru/post/1621674/


All Articles