Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native JS equivalent to jQuery delegation

What is the native implementation for event delegation on dynamically created dom elements?

I tried looking at the jQuery source but I can't follow the .on method.

Note: Currently I attach the event handlers after the dom elements are created, which seems pretty standard but I like the way jQuery .on handles dynamically created elements events with this syntax $( document ).on( "click", ".selector", handler );.

like image 244
Scott Mitchell Avatar asked Aug 11 '14 16:08

Scott Mitchell


2 Answers

What happens is basically this:

// $(document).on("click", <selector>, handler)
document.addEventListener("click", function(e) {
    for (var target=e.target; target && target!=this; target=target.parentNode) {
    // loop parent nodes from the target to the delegation node
        if (target.matches(<selector>)) {
            handler.call(target, e);
            break;
        }
    }
}, false);

However, e.currentTarget is document when the handler is called, and e.stop[Immediate]Propagation() will work differently. jQuery abstracts over that (including call order) a lot.

I've used the .matches() method, which is not yet standard but already available under different names in modern browsers. You might use a custom predicate to test elements instead of a selector. And addEventListener is obviously not oldIE-compatible.

like image 182
Bergi Avatar answered Sep 25 '22 01:09

Bergi


This should do it for you on a regular HTML element:

HTMLElement.prototype.on = function(event, selector, handler) {
    this.addEventListener(event, function(e) {
        let target = e.target;
        if (typeof(selector) === 'string') {
            while (!target.matches(selector) && target !== this) {
                target = target.parentElement;
            }

            if (target.matches(selector))
                handler.call(target, e);
        } else {
                selector.call(this, e);
        }
    });
};
like image 28
Data Crusader Avatar answered Sep 26 '22 01:09

Data Crusader