0

I have difficulties with event listeners and unbinding them. I have the following code:

function delegate(el, evt, sel, handler) {
    el.addEventListener(evt, function(event) {
        var t = event.target;
        while (t && t !== this) {
            if (t.matches(sel)) {
                handler.call(t, event);
            }
            t = t.parentNode;
        }
    });
}

And I apply the function like this:

function captureMouseDown() {
    console.log('mouse downed');
}

delegate(document, 'mousedown', '.js-flex', captureMouseDown);

How do I undelegate the event on the document and/or the selector js-flex

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
poashoas
  • 1,790
  • 2
  • 21
  • 44

1 Answers1

1

One option is to have delegate return the function passed to addEventListener, and then you can call removeEventListener with it:

function delegate(el, evt, sel, handler) {
    const listener = function(event) {
        var t = event.target;
        while (t && t !== this) {
            if (t.matches(sel)) {
                handler.call(t, event);
            }
            t = t.parentNode;
        }
    };
    el.addEventListener(evt, listener);
    return listener;
}

const listener = delegate(document, 'mousedown', '.js-flex', captureMouseDown);
// ...
document.removeEventListener('mousedown', listener);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320