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

375
Vistas
How to make an event callback that can also accept other types of inputs?

I have a callback that uses the event object to get a value and do stuff with it. I want to also pass the callback the value directly. There are many ways I can do this, but they all feel like bad code, here are a couple:

document.querySelector('div').onclick = log;

// Base Method Example
function log(event) { const id = event.target.id; console.log(id) } // Can't pass ID
// Wrapping
const execute = func => event => {
    const id = event.id;
    func.call(this, id);
}

document.querySelector('div').onclick = execute(log);

function log(id) { console.log(id) }
document.querySelector('div').onclick = log;

// Input type check
function log(input) {
   const id = (input instanceof Event)? input.target.id : input;
   console.log(id);
}
document.querySelector('div').onclick = log;

// Multiple inputs
function log(event, id) {
    const input = event? event.target.id : id 
    console.log(input);
}

log(undefined, 42)

Of these, I'm leaning towards either wrapping or type checking, but is there an even more concise way of doing this? Are there any known best practices in terms of handling this requirement?

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