Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'This' scope in TypeScript

On my webpage I have remove icons on rows in a table like this:

enter image description here

I am using TypeScript where I have attached an onClick listener to execute a function called OnRemoveClick, like this $('.remove').click(this.OnRemoveClick);

OnRemoveClick zeros 2 fields (on the row the remove icon is clicked) and then executes 2 functions, like this:

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 I have is that it falls over when I get to GetInputFieldsToJson I get:

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

I realise it is because this in the context of OnRemoveClick is attached to the HTMLAnchorElement which means I cannot access my functions from there.

What I have tried

I have tried setting the onClick listener with a lambda expression like this:

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

but that means that the two jQuery expressions to zero fields on the row no longer work

like image 534
NRKirby Avatar asked Jul 24 '15 07:07

NRKirby


1 Answers

As you might have already understood, the problem here is, when the event handler is invoked the default context as the dom element which triggered that event. So you are unable to invoke your object's method using that reference.

There are multiple solutions to this problem, one easy solution is to pass a custom context to the callback function using Function.bind() as given below and access the targeted element using Event.currentTarget in the callback like

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));
like image 171
Arun P Johny Avatar answered Oct 03 '22 03:10

Arun P Johny