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?
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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With