Jan Van Looveren Jan Van Looveren - 6 months ago 16
Javascript Question

convert javascript event this with typescript

I am converting my previous JavaScript code to typescript.
Now i am running into the following issue. When i convert the old prototype code to classes and methods inside typescript, i have an issue with events:
Consider following code:

// call this class, provide the parameter of the column
var self = this;
cell.onclick = function () {
self.makeTableSort(this); <== problem with parameter this.
};


The problem i have is that i need the object of the html element that is clicked.
where as "this" as parameter is not refering to the class object but to the html element.

EDIT:
I have already something tried like below:

// call this class, provide the parameter of the column
cell.onclick = (event) => {
this.makeTableSort(); <== missing parameter,
};


How do i convert this to TypeScript?

Answer

Try this:

cell.onclick = (event) => {
  this.makeTableSort(event.currentTarget);
};