'This' scope in TypeScript

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

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


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()); ie call the function.

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

链接地址: http://www.djcxy.com/p/86876.html

上一篇: 转换为NSMutableattributed字符串时,Bad Access崩溃

下一篇: '这'范围在TypeScript中