Native addEventListener with selector like .on() in jQuery

前端 未结 1 1865
予麋鹿
予麋鹿 2020-12-30 21:45

Does anyone know how jQuery\'s .on() method can be implemented in native JS? The \"addEventListener\" method does not take a child/selector element as a way to filter, and I

相关标签:
1条回答
  • 2020-12-30 22:07

    To perform event delegation natively:

    parent.addEventListener('click', function(e) {
        if(e.target.classList.contains('myclass')) {
            // this code will be executed only when elements with class 
            // 'myclass' are clicked on
        }
    });
    

    The efficiency you are referring to has to do with how many event handlers you add. Imagine a table with 100 rows. It is much more efficient to attach a single event handler to the table element then 'delegate' to each row than attach 100 event handlers, 1 to each row.

    The reason event delegation works is because a click event actually fires on both the child and the parent (because you're clicking over a region within the parent). The above code snippet fires on the parent's click event, but only executes when the condition returns true for the event target, thus simulating a directly attached event handler.

    Bubbling/capturing is a related issue, but you only need to worry about it if the order of multiple event handlers firing matters. I recommend reading further on event order if you are interested in understanding bubbling vs capturing.

    The most common benefit of event delegation is that it handles new elements that are added to the DOM after the event handler is attached. Take the above example of a table of 100 rows with click handlers. If we use direct event handler attachment (100 event handlers), then new rows that are added will need event handlers added manually. If we use delegated events, then new rows will automatically 'have' the event handler, because it's technically been added to the parent which will pick up all future events. Read What is DOM Event Delegation, as Felix Kling suggested, for more information.

    0 讨论(0)
提交回复
热议问题