Jquery event multiple triggers
Jquery event multiple triggers
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
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:
createdRow
which is triggered only once per row's lifetime$().off()
first.I would strongly suggest option 1!
Allan
Thank you again, Allan. I went for your option 1. Works like clockwork.