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