Challenge 3: A Stimulus Controller — Solution
// app/javascript/controllers/character_count_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["input", "count"]
update() {
this.countTarget.textContent = this.inputTarget.value.length
}
}
0
=begin
Notes:
- The controller file's name (character_count_controller.js) and the
data-controller="character-count" attribute must correspond -- Stimulus
converts the snake_case filename to the kebab-case identifier used in
HTML automatically.
- static targets = ["input", "count"] declares two named references;
data-character-count-target="input"/"count" on the actual elements is
what lets this.inputTarget and this.countTarget resolve to them inside
the controller.
- data-action="input->character-count#update" wires the textarea's native
input event (fired on every keystroke) to the controller's update
method -- the event name, controller name, and method name are all
encoded directly in that one attribute.
- update() reads the current value's length and writes it into the count
span's textContent -- a small, scoped DOM update, with no framework
re-render cycle and no client-side state beyond what's already in the
DOM.
=end