Currently, I am utilizing datatables (datatables.net) in Angular 5 and had set up a method to handle a click event on a tr
element as shown below:
const tableRef = this.table;
const routerRef = this.router;
this.table.on('click', 'tbody tr', function (e) {
const $tr = $(this).closest('tr');
const data = tableRef.row($tr).data();
if (data !== undefined) {
routerRef.navigateByUrl(`/some/url/details/${data.id}`);
}
});
Initially, my code closely resembled the example provided on datatables.net's website. However, I later decided to modify it to look like the one below:
this.table.on('click', 'tbody tr', this.rowClicked(this.table, this.router));
//...
private rowClicked(table, router: Router) {
return (e) => {
const $tr = $(this).closest('tr');
const data = table.row($tr).data();
if (data !== undefined) {
router.navigateByUrl('/some/url/details/`${data.id}`');
}
}
}
To my surprise, the revised version did not respond at all. Even after adding a console.log('row clicked');
within the lambda function, nothing happened besides the message being logged whenever a tr
was clicked. The variable data
always remained undefined
. I attempted using
$("#my-datatable-id").DataTable()
instead of table
, but still encountered no success. Upon further investigation, I noticed that the only disparity was in how the callback function was constructed (using the keyword function
). So, I made the switch and changed the lambda function to:
private rowClicked(table, router: Router) {
return function (e) {
// same logic as before
}
}
Surprisingly, this adjustment worked perfectly! It successfully retrieved the data from the tr
element. Can someone explain why I couldn't retrieve the data
with the lambda function, yet could do so with the function
construct? Thank you in advance!