Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Using jquery $(this) in event

HTML:

<div>
<button data-id="3">Click Me</button>
</div>

In classic jQuery I would do:

$("div").on("click","button", test);

function test(){
   alert($(this).data("id"));
}

To get the data-id of the clicked element

In TypeScript (in a class) I use:

class foo { ...
 $("div").on("click", "button", (event) => this.test());

 public test(){
    alert($(this).data("id")); // "undefined"
    console.log($(this));
 }

....
}

Here I don't get the clicked element - $(this) is the instance of the class.

What did I do wrong?

like image 262
mdunisch Avatar asked Apr 03 '14 16:04

mdunisch


3 Answers

According to Typescript's spec "this" is referring to the instance of class the method belongs to/is called on.

You could use the target attribute of the event object passed to the callback:

class foo {
  public test(evt){
    alert($(evt.target).data("id")); // "undefined"
    console.log($(evt.target));
  }
}

Or event.currentTarget depending on if you want to get the element actually clicked on or the element which captured the event.

like image 89
Laszlo Korte Avatar answered Oct 13 '22 12:10

Laszlo Korte


Using event.currentTarget worked for me when trying to get a data attribute of what was clicked.

$('.elementID').click(e => this.clickedElement(e));


clickedElement(e: JQueryEventObject) {
    var iWasClickedData = $(this).data('key'); // will not work
    var iwasClickedDataFixed = $(e.currentTarget).data('key'); // will work
}
like image 22
Billy Avatar answered Oct 13 '22 13:10

Billy


By using arrow functions (event) => TypeScript is giving you a lexically bound this. (In compiled code a previously captured instance called _this)

If you switch to using vanilla function syntax you should be able to use $(this) as you would normally:

$("div").on("click", "button", function(event) { this.test()});

Obviously you have an issue with the instance of the test method being called but I thought it worth sharing.

like image 4
John Reilly Avatar answered Oct 13 '22 13:10

John Reilly