We've got a Web App where we have a lot (>50) of little WebComponents that interact with each other.
To keep everything decoupled, we have as a rule that no component can directly reference another. Instead, components fire events which are then (in the "main" app) wired to call another component's methods.
As time went by more and more components where added and the "main" app file became littered with code chunks looking like this:
buttonsToolbar.addEventListener('request-toggle-contact-form-modal', () => {
contactForm.toggle()
})
buttonsToolbar.addEventListener('request-toggle-bug-reporter-modal', () => {
bugReporter.toggle()
})
// ... etc
To ameliorate this we grouped similar functionality together, in a Class
, name it something relevant, pass the participating elements when instantiating and handle the "wiring" within the Class
, like so:
class Contact {
constructor(contactForm, bugReporter, buttonsToolbar) {
this.contactForm = contactForm
this.bugReporterForm = bugReporterForm
this.buttonsToolbar = buttonsToolbar
this.buttonsToolbar
.addEventListener('request-toggle-contact-form-modal', () => {
this.toggleContactForm()
})
this.buttonsToolbar
.addEventListener('request-toggle-bug-reporter-modal', () => {
this.toggleBugReporterForm()
})
}
toggleContactForm() {
this.contactForm.toggle()
}
toggleBugReporterForm() {
this.bugReporterForm.toggle()
}
}
and we instantiate like so:
<html>
<contact-form></contact-form>
<bug-reporter></bug-reporter>
<script>
const contact = new Contact(
document.querySelector('contact-form'),
document.querySelector('bug-form')
)
</script>
</html>
I'm really weary of introducing patterns of my own, especially ones that aren't really OOP-y since I'm using Classes
as mere initialisation containers, for lack of a better word.
Is there a better/more well known defined pattern for handling this type of tasks that I'm missing?