Do you follow a general style guide when writing Stimulus Controllers?

I’m curious, do you use a style guide for common patterns when writing your Stimulus Controllers? Not necessarily syntax, but maybe when to use what tools?

For example:

  • When do you use getters and setters or only controller values?
  • Do you prefer increasing a controller’s scope to target common elements, or do you query the DOM?
  • When dispatching custom events, are there any good conventions to follow?

I’m thinking it could be useful to have some general guidelines for teams, but I haven’t come across anything like this.

Following as I am also interested. I know there are a few resources out there, most notably Better Stimulus.

I can answer your second question from my team’s perspective. If it is reasonable to expand the scope to allow targets to be defined, that is always the preference. If something requires a DOM query, it has to have a very good reason, otherwise it is considered an indication of poor design. This allows for very specific edge cases while also encouraging our team to really think through their implementation.

1 Like
  1. I usually use values only
  2. If I can use the target then I will use it, otherwise I will query the DOM
  3. I usually put controller name like:
document.dispatchEvent(new CustomEvent("name--controller:eventName", {
     detail: { }, bubbles: true, cancellable: true }
1 Like

@ruby_chille - Not sure if you were aware that recent versions of stimulus include a helper method in the Controller base class to make dispatching namespaced events easier:

this.dispatch('myEvent'); //=> controllerName:myEvent

see: stimulus/controller.ts at main · hotwired/stimulus · GitHub