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

137
Visualizações
Adding event listeners for dynamic items in an MVC structure?

I know how to add event listeners to dynamically created elements, but I'm having a bit of a mental block doing it in an MVC pattern.

So my controller tells the view to open a modal with several elements/cards. Each card has a button. Pressing the button replaces the card with another newly created card. Something like this:

// Controller.js

if(response.data) {
    view.renderModal(response.data);
    this.addModalListeners();
}
...
function addModalListeners() {
    // Select the elements' btns, loop over them adding logic
    const btns = document.querySelector('.btns');
    btns.forEach(btn => {
        btn.addEventListener('click', () => {
            // do things here that the element needs
            view.replaceTheElementThatContainsThisButton(// pass that info);
        })
    })
}

So basically my problem is the Controller sets the logic for the btns clicks. But the view is responsible for replacing the element.

  • I could add a listener to the new element's button in the view, but then I don't have access to the data in the Controller.

  • I could also create the new element in the Controller, add the listener, and then pass it to the view, but creating a DOM element doesn't feel like the Controller's responsibility?

I'm sure there's an obvious solution, but I can't yet see it

Any help would be appreciated

*Edit: I guess I could also have the logic in a separate function in the controller and pass it to the view? This feels like the best answer I can think of so far

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