Jquery event multiple triggers

Jquery event multiple triggers

matolamatola Posts: 23Questions: 6Answers: 1
edited November 2015 in DataTables 1.10

Hi, there,
I tested the code snippet below, typing a search string in the search/filter box. Depending on how many characters I typed, when I then click on the filtered item I get as many console printouts of "hi there" as there are characters in the box. Which means that the onclick function is run that many times instead of only one. What is wrong with this?

var oTable = $('#doc').dataTable( {
    fnRowCallback: function( nRow, sData, aData, iDisplayIndex, iDisplayIndexFull ) { 
        $("td:eq(0)",nRow).on('click', function() { 
            console.log("hi there");
            }
        );
    }, ....

});    

I believe there is something I don't understand about how DataTables functions.

Best Regards,
Mats

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,695Questions: 1Answers: 10,500 Site admin
    Answer ✓

    This isn't really an issue with DataTables, but more that you are binding a new event listener every time to row callback is activated. As the rowCallback documentation states, the function is called every time a row is displayed - so if the row is displayed 5 times (paging, sorting, filtering, whatever) you are going to be adding 5 event listeners!

    There are three options:

    1. Use a delegated event listener like in this example
    2. Use createdRow which is triggered only once per row's lifetime
    3. Remove the old events using $().off() first.

    I would strongly suggest option 1!

    Allan

  • matolamatola Posts: 23Questions: 6Answers: 1
    edited December 2015

    Thank you again, Allan. I went for your option 1. Works like clockwork.

This discussion has been closed.