Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!