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

93
Views
Manejar eventos con una clase

Me gusta manejar eventos dentro de una clase. Es decir, necesito acceder a mi instancia en el controlador de eventos y usar datos encapsulados dentro de la instancia. Cuando se activa un evento, this se convierte en el HTMLElement como se esperaba. No pude encontrar un buen método para llegar a la instancia asociada con el elemento.

Una variable global no ayuda si hay dos instancias de la clase asignadas a dos botones. En este código de muestra, el botón B1 aumenta p2 en lugar de 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!