-1

Consider this piece of TypeScript code which relies on the JQuery library:

class Alpha {
    public foo() {
        $('.ca').click(() => {console.log(this)});
        $('.cb').click(function () {console.log(this)});
    }
}

Assume that $('.ca') and $('.cb') refer to two buttons.

After calling foo on an Alpha object, we see that the click handler for '.ca' prints the Alpha object, whereas the click handler for '.cb' prints the button identified by $('.cb').

Both of these different interpretations of this can be useful. But what do I do if I want to use both versions of this inside a handler? In other words, I want to access both the Alpha object and the '.cb' button inside the handler.

EDIT

To clarify: I should have emphasized that I'm specifically interested in a way to access the '.ca' button in the situation where I'm using the => notation.

User Matt U indicated this in his answer to my question.

oz1cz
  • 5,504
  • 6
  • 38
  • 58

2 Answers2

2

You can use the event object with the arrow function to get the element (e.g. the button with class .cb) that triggered the click event, while this will refer to the class. Such as:

class Alpha {
  foo() {
    $('.cb').click(event => {
      console.log(this);
      console.log(event.target.className);
    }
  }
}

See here for a working example.

Matt U
  • 4,970
  • 9
  • 28
1

Why it works like that can be answered with this.

TLDR : Inside event handlers, this is the element on which the event is attached. All function types (except arrow functions), this depends on how they are invoked and belong to the invoker. Arrow functions take this from the lexical scope of their declaration (Here the object instance).

You can keep a reference of the this in another variable, and taking advantage of closures use that inside your event handler.

class Alpha {
    public foo() {
        let context = this;
        $('.ca').click(function () {
        console.log(context); console.log(this); });
    }
}
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39