Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
Handle events with a class

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();
    }
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!