0

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

NickW
  • 1,207
  • 1
  • 12
  • 52
  • 1
    Why not use [event delegation](https://davidwalsh.name/event-delegate) and then you don't need to worry about when elements are added to the DOM. – Heretic Monkey Oct 12 '21 at 20:22
  • Honestly, I swear this is something I *always* miss. Stack overflow needs a facepalm emoji. Cheers – NickW Oct 12 '21 at 20:29
  • Oh, and if you want to put it as an answer I'll select :) – NickW Oct 12 '21 at 20:29
  • 1
    Duplicate: [Attach event to dynamic elements in javascript](https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript) –  Oct 12 '21 at 20:30

0 Answers0