Which is the most efficent way to handle eventListeners?

I wrote the following code:

document.addEventListener('click', function (event) {
       if(event.target.matches('#open-new-not') || event.target.matches('#close-not')){
            opnNewNot();
       }
       if(event.target-matcheS('#hide-links')){
            hideLinks();
       }
       if(...and so on...){}
});

Is it a good solution? Could you please advise how could I handle almost all the eventlisteners in the most simple and efficient way? Many thanks.

2 answers

  • answered 2018-11-07 22:39 Benjamin Brettsworth

    If you absolutely must go this route then I suggest that you use a switch statement as opposed to a string of ifs. Doing so has the added benefit of not interrupting the handling of other events that you are not trying to intercept.

    document.addEventListener('click', function (event) {
        switch (event.target.id) {
            case 'open-new-not':
            case 'close-not':
                openNewNot();
                break;
            case 'hide-links':
                hideLinks();
                break;
            // etc
        }
    });
    

    If I were you though I would heavily consider whether or not I want to capture every click event on every element or if I could realistically get away with targeting just a handful of select elements.

  • answered 2018-11-07 22:43 Bergi

    Since you are matching only ids, there's no point in using event delegation (unless the elements are lazily loaded). Just install the event listeners on the elements themselves, don't use a large chain of if/else here. Event delegation only makes handling events on many similar elements more efficient.