'This' scope in TypeScript

On my webpage, I delete the icons in the rows in the table as follows:

enter image description here

I use TypeScript, where I connected the onClick to execute a function called OnRemoveClick , for example, $('.remove').click(this.OnRemoveClick);

OnRemoveClick zeros 2 fields (in the line click the delete icon), and then performs 2 functions, for example:

 private OnRemoveClick(): void { $(this).parents('tr').find('.input-qty').val('0'); $(this).parents('tr').find('.sub-total').html('0'); this.GetInputFieldsToJson(); this.CalculateTotal(); } 

The problem is that it crashes when I get to GetInputFieldsToJson , I get:

TypeError: this.GetInputFieldsToJson is not a function when HTMLAnchorElement.Index.OnRemoveClick

I understand, because this in the context of OnRemoveClick tied to HTMLAnchorElement , which means that I cannot access my functions from there.

What i tried

I tried setting up the onClick listener using a lambda expression like this:

$('.remove').click(() => this.OnRemoveClick);

but that means two jQuery expressions for null fields in a string no longer work

+7
javascript jquery this typescript
source share
2 answers

As you may have already understood, the problem here is that when the event handler is called by the default context as the dom element that raised this event. Therefore, you cannot call your object method using this link.

There are several solutions to this problem, one simple solution is to pass a custom context to the callback function using the Function.bind () function, as described below, and access the target element using Event.currentTarget in the callback, for example

 private OnRemoveClick(e): void { $(e.currentTarget).parents('tr').find('.input-qty').val('0'); $(e.currentTarget).parents('tr').find('.sub-total').html('0'); this.GetInputFieldsToJson(); this.CalculateTotal(); } 

then

 $('.remove').click(this.OnRemoveClick.bind(this)); 
+5
source share

$('.remove').click(() => this.OnRemoveClick); should be $('.remove').click(() => this.OnRemoveClick()); , i.e. call a function.

More on this : https://www.youtube.com/watch?v=tvocUcbCupA

-one
source share

All Articles