In my current Angular project, I am utilizing Datatables and buttons to manipulate data. The buttons available are "View", "Mark as completed", and "Mark as incomplete" which trigger specific functions when clicked. To achieve this functionality, the following code is used:
/**
* Hides ID and adds onclick functionality
*/
ngAfterViewInit() {
const table = $('.display').DataTable({
responsive: true,
bRetrieve: true
});
table.column(0).visible(false);
this.clickListener(table, this.route);
}
/**
* Listens to row click
*/
clickListener(table: any, route: any) {
const self = this;
let rowData;
$('.display').on('click', 'tbody tr td .view', function(e) {
rowData = self.checkIfRowsHidden(table, this, e);
self.router.navigate([route + '/detail/' + rowData[0]]);
});
$('.display').on('click', 'tbody tr td .done', function(e) {
rowData = self.checkIfRowsHidden(table, this, e);
self.executePutData(rowData[0], 'Completed', self);
});
$('.display').on('click', 'tbody tr td .undone', function(e) {
rowData = self.checkIfRowsHidden(table, this, e);
self.executePutData(rowData[0], 'In Progress', self);
});
}
The usage of var self = this
, serves as a reference to the global scope. Additionally, within the function checkIfRowsHidden
, this
is used to capture the local scope. This function operates using the local scope in the following manner:
checkIfRowsHidden(table, scope, event) {
event.stopImmediatePropagation();
if (table.responsive.hasHidden()) {
const parentRow = $(scope).closest("tr").prev()[0];
return table.row( parentRow ).data();
} else {
return table.row($(scope).closest('tr')).data();
}
}
In an effort to utilize binding instead of self
, I attempted to modify the clickListener
function in this way:
clickListener(table: any, route: any) {
let rowData;
$('.display').on('click', 'tbody tr td .view', function(e) {
rowData = this.checkIfRowsHidden(table, this, e);
this.router.navigate([route + '/detail/' + rowData[0]]);
}.bind(this));
/*rest of the code
.
.
*/
However, due to the presence of multiple scopes, the use of this
from both the local and global scopes caused errors when fetching data from tables. Is there a method to bind the global scope only to specific items, or is it necessary to resort back to using var self=this
?