'This' scope in TypeScript 'This' scope in TypeScript typescript typescript

'This' scope in TypeScript


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));


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

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