🎮
Stimulus
HTML 중심의 경량 JavaScript 프레임워크
Stimulus는 Hotwire의 JavaScript 프레임워크로, HTML에 속성을 추가하여 JS 동작을 선언적으로 연결합니다.
<div data-controller="hello">
<input data-hello-target="name" type="text">
<button data-action="click->hello#greet">Greet</button>
<span data-hello-target="output"></span>
</div>
// app/javascript/controllers/hello_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["name", "output"]
greet() {
this.outputTarget.textContent =
`Hello, ${this.nameTarget.value}!`
}
}
3가지 핵심 개념:
Controller:
data-controller="name"— JS 컨트롤러 연결Action:
data-action="event->controller#method"— 이벤트→메서드 매핑Target:
data-controller-target="name"— DOM 요소 참조
추가: Values (data-controller-value-name), Classes (data-controller-class-name), Outlets (다른 컨트롤러 참조)
핵심 포인트
1
data-controller="name"으로 HTML 요소에 컨트롤러 연결
2
static targets = ["output"] 정의 → data-name-target="output" 으로 DOM 참조
3
data-action="click->name#method" 으로 이벤트 핸들러 연결
4
connect() — 컨트롤러가 DOM에 연결될 때 자동 호출
5
disconnect() — DOM에서 제거될 때 자동 호출 (정리 작업)
6
static values로 HTML 속성에서 데이터 전달 (data-name-url-value="...")
장점
- ✓ HTML 중심 — 서버 렌더링과 자연스럽게 결합
- ✓ 경량 (React/Vue 대비 매우 작음)
- ✓ Turbo와 완벽 호환
- ✓ 학습 곡선 낮음
단점
- ✗ 복잡한 클라이언트 로직에는 한계
- ✗ SPA 수준의 상태 관리 어려움
- ✗ React/Vue 생태계 대비 작은 커뮤니티
- ✗ 컨트롤러 간 통신이 복잡할 수 있음
사용 사례
드롭다운/모달 토글
폼 실시간 검증
클립보드 복사 버튼
탭 전환
Ajax 기반 자동 완성