What is Stimulus and how does it work?
mainStimulus is a JavaScript framework designed to enhance existing static or server-rendered HTML. Instead of managing the entire DOM, Stimulus connects JavaScript objects called controllers to HTML elements using data-controller attributes.
Core Concepts
Stimulus relies on four primary abstractions to bridge HTML and JavaScript:
- Controllers: JavaScript classes that manage a specific piece of behavior. Stimulus instantiates a controller when it detects a
data-controllerattribute on an element. - Actions: Connect controller methods to DOM events using
data-actionattributes (e.g., connecting aclickevent to a method). - Targets: A way to locate and reference specific elements within a controller's scope.
- Values: A mechanism to read, write, and observe data attributes on the controller's element, allowing data to flow between the HTML and the JavaScript logic.
This approach separates content from behavior, similar to how CSS separates content from presentation.