I was reviewing my code for one of my projects when I noticed that one of my function's name is coloured green while all of the other functions are yellow.
When I hover over the function in the readButton.addEventListener("click", toggleRead);
it says: Class toggleRead - function toggleRead(e: any): void
Also, when I hover over the actual function declaration, it says This constructor function may be converted to a class declaration.ts(80002)
I am using the toggleRead
function to toggle an attribute. The this
keyword refers to the button that calls the function. It doesn't seem to cause any issues in my program and it is working as intended.
Am I breaking some kind of code convention that results in this hint, or am I otherwise doing something wrong? Also, why does visual studio think this function is a constructor?
I found this question on stack overflow but the person asking the question is only interested in turning the hint off. I want to know if I did something wrong.
readButton.addEventListener("click", toggleRead);
// Toggle book read
function toggleRead(e) {
const bookIndex = getBookIndex(this);
const bookObject = library.at(bookIndex);
if (bookObject.read) {
bookObject.read = false;
this.setAttribute("is-read", "false");
this.innerHTML = "Unread";
} else {
bookObject.read = true;
this.setAttribute("is-read", "true");
this.innerHTML = "Read";
}
}
I wanted to post Raymond's recommendation from their comment under my question as this resolved the issue for me:
The solution was to replace this
with the more idiomatic e.currentTarget
.
// Toggle book read
function toggleRead(e) {
const bookIndex = getBookIndex(e.currentTarget);
const bookObject = library.at(bookIndex);
if (bookObject.read) {
bookObject.read = false;
e.currentTarget.setAttribute("is-read", "false");
e.currentTarget.innerHTML = "Unread";
} else {
bookObject.read = true;
e.currentTarget.setAttribute("is-read", "true");
e.currentTarget.innerHTML = "Read";
}
}