Event Delegation

Event delegation is extremely useful in cases you treat with dynamic content.

Example 1
import {delegate, delegateRemove} from 'BobjollPath/library/dom';

    delegate(
        selector: string, 
        eventType: Event['type'], 
        eventHandler: Function, 
        elementScope: HTMLElement | Document = document
    );

    delegateRemove(
        selector: string, 
        eventType: Event['type'], 
        eventHandler: Function, 
        elementScope: HTMLElement | Document = document
    );
Example 2
let button = document.getElementById('insert-dynamic-element');

    if (button) {
        let random = ['button', 'form', 'a'];
        let randomCount = 0;

        delegate('.dynamic-elements', 'click', dynamicElementsClickHandler);

        button.addEventListener('click', function() {
            let elementType = random[Math.floor( Math.random() * random.length )];
            let element = document.createElement(elementType);

            element.classList.add('dynamic-elements', 'block', 'pd-lv2');
            element.setAttribute('data-click-text', `You just clicked on a ${elementType}, generated dynamically.`);
            element.innerHTML = `Dynamic generated ${elementType} number ${randomCount}.`;

            button.insertAdjacentElement('afterend', element);

            randomCount++;
        });

        function dynamicElementsClickHandler() {
            alert(this.getAttribute('data-click-text'));
        }
    }