Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

92
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda