Controller versus Components

Hello community !

I have been using Stimulus for about a year now and really love it so far !

Having a project that significantly grew up in size, I start to see some common coding patterns I would like to improve in order to increase code quality and readability

Here’s an example:

I have the need for several forms on my app to prevent the default submission behavior.

I started implementing this common behaviour using a small stimulus controller:

// form_submission.js
import { Controller } from 'stimulus'
   
export default class extends Controller {
  
  preventFormSubmission(e) {
    e.preventDefault()
  }
}

// form.html
<form data-controller="form-submission" data-action="form-submission#preventFormSubmission"></form>

Having done som iOS development in the past, I can’t help but think of the Stimulus Controller as an orchestrator between components, that are defined in their own class. Creating so little logic in the controller feels wrong and I’d like to know if there is a better alternative to avoid the multiplication of small one-purposed stimulus controllers in my app and still take advantage of the stimulus observers.

An idea I had was to use an AppController, binded to the root of the document which would initialize all my small components :

// app_controller.js
import { Controller } from 'stimulus'
   
export default class extends Controller {
  static targets = [  "components" ]

  initialize() {
   this.componentsTargets.foreach((comp) => {
     // initialize the component based on his data-component value
   )}
}

I would however need a lifecycle events for targets added or removed from the dom to mount or unmount the components and I don’t think it’s part of the current stimulus API

I’d love to have some feedback about your way of doing !