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

107
Visualizações
Global onclick handler vs. per-element event handlers

Consider this example:
You're creating a website that uses client-side rendering. When the user clicks a link, you want to disable the browser's navigation and render the new page yourself.

Perhaps you also have some html like this, and you want to call upvote_post(id) every time the button is clicked:

<post-element data-id=12345> 
   ... 
   <upvote-button></upvote-button>
</post-element>

The common way to handle both of these cases would be to add a click event handler on every <a>, <upvote-button>, etc. element that you generate.

But wouldn't it be better to just add an event handler on the document itself?

document.addEventListener('click', function(e) {
    for (let elem of e.path) {
        if (elem instanceof HTMLAnchorElement && elem.origin==window.location.origin) {
            e.preventDefault()
            render_page(elem.href)
            break
        } else if (elem.tagName=='UPVOTE-BUTTON') {
            let post = elem.closest('post-element')
            upvote_post(post.dataset.id)
            break
        }
    }
})

Of course, it feels wrong to bypass the builtin event handler system, but I can't think of any disadvantages here.
You can still add event handlers to specific elements if you need to, but for common actions, this seems like a better solution.

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