I like to handle events within a class. That is, I need to access my instance in the event handler and use data encapsulated within the instance. When an event is triggered, this becomes the HTMLElement as expected. I could not find a nice method to reach the instance associated with the element.
A global variable does not help if there are two instances of the class assigned to two buttons. In this sample code button B1 increases p2 rather than p1.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="increment.js"></script>
</head>
<body>
<p>p1: <span id="idP1">1</span></p>
<p>p2: <span id="idP2">2</span></p>
<button id="idB1">B1</button>
<button id="idB2">B2</button>
<script>
const p1 = document.querySelector("#idP1");
const p2 = document.querySelector("#idP2");
const b1 = document.querySelector("#idB1");
const b2 = document.querySelector("#idB2");
const i1 = new Increment(p1, b1, 100);
const i2 = new Increment(p2, b2, 200);
</script>
</body>
</html>
let increment: Increment;
class Increment {
target: HTMLElement;
data = 0;
constructor(target: HTMLElement, button: HTMLElement, initialValue: number) {
increment = this; // problem
this.target = target;
this.data = initialValue;
this.someDataUpdate();
button.addEventListener("click", this.eventHandler);
}
eventHandler(e: Event) {
console.log("e.target:", e.target);
console.log("this:", this);
console.log("increment.date:", increment.data);
increment.someDataUpdate();
// this.plusOne(); // produces error
}
someDataUpdate() {
this.data += 2;
this.target.innerHTML = (this.data).toString();
}
}