Event delegation

One other way developers can easily create unnecessary strain on the user's browser is by creating too many event handlers. For instance, let's say you want to create a large table (perhaps 20 rows × 20 columns), so you create a parent View for the table and a large number of child Views for each cell. So far so good! Now let's say, you add a click event handler to each of these child Views. Without realizing it, you just created 400 event handlers. If you add another event handler, such as a change handler for <input> elements inside the cell, you add another 400, and so on.

Given enough Views and enough event handlers, this can eventually create a performance issue, but luckily, JavaScript comes with a built-in mechanism that we can use to solve this problem: event bubbling. Whenever an event occurs in the DOM, it first triggers event handlers on the relevant DOM element and then bubbles up to each successive parent of that element. In other words, if a click event occurs on a <td> element, the browser will resolve any event handlers bound to that <td> element first, then (unless one of the event handlers returned false) it will call the handlers on the <td> element's parent <tr> element and then that <tr> parent's <table>:

$(document.body).append('<table><tr><td></td></tr></table>'),
$('td').on('click', function(e) {
    e.target; // will be the td element
    e.currentTarget; // will also be the td element
});
$('tr').on('click', function(e) {
    e.target; // will still be the td element
    e.currentTarget; // will be the tr element
});
$('table').on('click', function(e) {
    e.target; // will still be the td element
    e.currentTarget; // will be the table element
});
$('td').click(); // first the td handler will trigger, then the tr
                 // handler, and finally the table handler

We can take advantage of this fact and change our event binding strategy to improve performance by binding our events to the parent table element's View rather than to each child View. This parent View event handler can then trigger the appropriate logic on the relevant child View by using the event's target property to determine which child View caused the event. While this approach requires slightly more work, it allows us to reduce our 400 click event handlers down to a single event handler, and on particularly complex pages (such as our hypothetical table page), the use of such event delegation can significantly reduce the strain on the browser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.84.171