【发布时间】:2020-10-02 04:13:09
【问题描述】:
我目前正在使用 Angular 构建一个应用程序,该应用程序使用 Datatables 中的按钮来操作数据。我可用的当前按钮是“查看”“标记为已完成”,“标记为未完成”,单击触发特定功能。相关功能正在通过以下方式实现:
/**
* 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);
});
}
如您所见,我使用var self = this 来创建对全局范围的引用。另请注意,我还在函数checkIfRowsHidden 中使用this 来捕获本地范围。该函数使用这样的本地范围:
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();
}
}
我最近向自己介绍了使用绑定而不是 self 作为一种更有条理且可能更节省内存的方式。我尝试通过将其修改为以下内容在我的clickListener 函数中使用它:
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
.
.
*/
不幸的是,由于我一直在使用多个范围,因此本地和全局范围中的 this 被视为相同,从而在从表中检索数据时产生错误。有没有办法将全局范围绑定到特定项目?还是我必须求助于var self=this?
【问题讨论】:
-
由于 JQuery 和 Angular 的混合,它可能会被否决。它通常是不受欢迎的。尝试使用 Angular
Renderer2和ElementRef。 -
我投票结束这个问题,因为它有糟糕的编码约定,这在社区中是不可接受的
标签: javascript angular typescript