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

378
Visualizações
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 à 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