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

109
Visualizações
Replace multiple click handlers with a single click handler

I'm wondering if it's possible to clean up these click events a bit:

$(document)
    .on('click', '.newGameItem', getNewGameItem)
    .on('click', '.startGame', startThisGame)
    .on('click', '.showThisGameInfo', showThisGameInfo)
    .on('click', '.closeThisGameInfo', closeThisGameInfo)
    .on('click', '#api_game_test', testApiGame)
    .on('click', '.nextGame', shiftGames)
    .on('click', '.confirm_cancel', cancelLexTimer)
    .on('click', '.completed_submission', reload)
    .on('turbolinks:load', function() { ... });

The first 8 methods in the chain are click events—is there a way in javascript to combine these under one click "umbrella" even though the click events are delegated to different elements

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could use a single .click and check the target of the click with the event argument:

$(document).on('click', function (event) {
  var target = event.target;

  if ($(target).hasClass('newGameItem')) getNewGameItem();
  if ($(target).hasClass('startGame')) startThisGame();

  if (target.id == 'api_game_test') testApiGame();

  // etc
})

Here is the doc (quite poor) about jQuery's event.target: api.jquery.com/event.target

about 4 years ago · Santiago Trujillo Relatório

0

You're not going to get away from a big block of something, be it .on or GG's answer. You could always put it in a separate .js file to separate it so it's not cluttering up your code.

// in addHandlers.js
function addHandlers(document) {
    document.on('click',...
}

This will clean up your code while getting all of that non-essential clutter out of the way while you're doing the fun stuff.

about 4 years ago · Santiago Trujillo Relatório
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