Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda