0

I have the following event handler defined:

$('#current-tab').click(myCode.handleTabClick);

And in that function I have

handleTabClick: (): void => {
    const identifier: string = $(this).attr('id');
},

When I execute this in the browser, the event gets fired but I see identifier is "undefined". However, if I add a break-point and then copy $(this).attr('id') into the browser's console, I see that this resolves to "current-tab".

Why can't I capture this into my constant variable?

4
  • Can you create a minimal reproducible example? It is very hard to tell from the information you provided. Commented Dec 8, 2020 at 16:37
  • 2
    Handle click is an arrow function. Change it to a regular function. The “this” context is not bound to the function in an arrow function Commented Dec 8, 2020 at 16:38
  • Check this answer. Commented Dec 8, 2020 at 16:39
  • stackoverflow.com/questions/34361379/… Commented Dec 8, 2020 at 16:46

1 Answer 1

1

Change:

handleTabClick: (): void => {
    const identifier: string = $(this).attr('id');

},

To:

handleTabClick: function(): void {
    const identifier: string = $(this).attr('id');
}

In a an arrow function this is not bound to the function

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.