[英]Can't access reference to typescript method from DataTable method
I am connecting a datatable from datatables.net with my Angular app where I am trying to get data fra a row in typescript. 我正在使用我的Angular应用程序从datatables.net连接一个数据表,在该应用程序中我试图从打字稿中获取一行数据。 I can see the data through the console, but I can't reach my other methods in the class.
我可以通过控制台查看数据,但是无法访问该类中的其他方法。
So i tried to .bind(this) on the table.on() method but did not help. 所以我试图对table.on()方法进行.bind(this),但没有帮助。
var table = $('#datatable').DataTable();
// Edit record
table.on('click', '.edit', function() {
let $tr = $(this).closest('tr');
var data = table.row($tr).data();
console.log(data[0]);
this.navigateTo(data[0]);
}.bind(this));
But i receive following error: 但是我收到以下错误:
ERROR TypeError: Cannot read property '0' of undefined
So I need a symbol from data from data[0] to pass on to another component. 因此,我需要来自data [0]的数据中的符号来传递给另一个组件。 But then this error shows.
但是随后出现此错误。
What am I doing wrong? 我究竟做错了什么? I guess it is something with the .bind(this), but i am not sure.
我想这与.bind(this)有关,但我不确定。
Thanks in advance. 提前致谢。
The problem is that the event handling in jQuery relies on changing the this
in the scope of the function. 问题在于jQuery中的事件处理依赖于在函数范围内更改
this
。 When you attach the click event handler to .edit
, jQuery will try to call the handler passing the clicked DOM element as this
. 当您将click事件处理程序
.edit
,jQuery将尝试调用句柄传递点击DOM元素作为this
。 That is necessary for your code cause you are using the clicked element in $(this).closest('tr');
这对您的代码来说是必要的,因为您正在
$(this).closest('tr');
中使用clicked元素$(this).closest('tr');
. 。
When you add .bind(this)
you prevent jQuery from "replacing" the this
when calling the handler. 当添加
.bind(this)
可以防止jQuery在调用处理程序时“替换” this
。 In this case this
will be the same as it was when .bind(this)
was called. 在这种情况下,
this
与调用.bind(this)
时相同。
There are a few ways you can workaround this situation: 有几种方法可以解决这种情况:
Create a reference to the outer this
: 创建对外部
this
的引用:
var table = $('#datatable').DataTable(); var that = this; // Edit record table.on('click', '.edit', function() { let $tr = $(this).closest('tr'); var data = table.row($tr).data(); console.log(data[0]); that.navigateTo(data[0]); });
Keep the binding, but use the event target instead of this
: 保持绑定,但使用事件目标代替
this
目标:
var table = $('#datatable').DataTable(); // Edit record table.on('click', '.edit', function(event) { let $tr = $(event.target).closest('tr'); var data = table.row($tr).data(); console.log(data[0]); this.navigateTo(data[0]); }.bind(this));
Use arrow function to keep the outer this, and get the clicked element from the event: 使用箭头功能保留外部元素,并从事件中获取clicked元素:
var table = $('#datatable').DataTable(); // Edit record table.on('click', '.edit', event => { let $tr = $(event.target).closest('tr'); var data = table.row($tr).data(); console.log(data[0]); this.navigateTo(data[0]); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.