Event handling test

A comparison between direct handler attachment and event delegation.

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<h1>Event handling test</h1>
<p>Add rows to both tables and see the difference in handling.</p>
<p>Event delegation attaches a single event listener and events related to newly added children are caught.</p>
<p>Direct event handling attaches an event handler to each child, where children added after the inital handler attachment don't have a handler attached to them, and therefore their indices won't be logged to console.</p>
<h2>Delegation</h2>
<button data-action="add-row" data-table="table-delegate">Add row to delegation</button>
<table id="table-delegate" class="table">
    <tbody>
    <tr>
        <td>normal</td>
        <td>normal</td>
        <td>normal</td>
    </tr>
    <tr>
        <td><p>nested</p></td>
        <td><p>nested</p></td>
        <td><p>nested</p></td>
    </tr>
    <tr>
        <td>normal</td>
        <td>normal</td>
        <td><p>nested</p></td>
    </tr>

</table>

<h2>Direct attachment</h2>
<button data-action="add-row" data-table="table-direct">Add row to direct</button>
<table id="table-direct" class="table">
<tbody>
    <tr>
        <td>normal</td>
        <td>normal</td>
        <td>normal</td>
    </tr>
    <tr>
        <td><p>nested</p></td>
        <td><p>nested</p></td>
        <td><p>nested</p></td>
    </tr>
    <tr>
        <td>normal</td>
        <td>normal</td>
        <td><p>nested</p></td>
    </tr>
    
</tbody>
</table>

CSS

tr:hover{
    background:#ddd;
}

button {
    margin-bottom: 5px;
}

JavaScript

$("#table-delegate").on("click", "tr", function(e) {
    console.log('delegated', $(e.currentTarget).index() + 1);
});

$("#table-direct tr").on("click", function(e) {
    console.log('direct', $(e.currentTarget).index() + 1);
});

$('[data-action=add-row]').click(function(e) {
    var id = e.target.dataset.table;
    $('#' + id + ' tbody')
        .append($('<tr><td>extra</td><td>extra</td><td>extra</td></tr>')[0])
});

$(".table tr").click(function(){
$(this).closest('tr').addClass('clicked');
})