핵심 개념
StimulusReflex는 WebSockets(ActionCable) 및 CableReady를 사용하여 Rails 애플리케이션에서 반응형 실시간 사용자 인터페이스를 제공합니다.
기본 Reflex
<!-- view.html.erb -->
<button data-reflex="click->Counter#increment">Increment</button>
# app/reflexes/counter_reflex.rb
class CounterReflex < ApplicationReflex
def increment
@count = element.dataset[:count].to_i + 1
end
end
Morph 모드
Page Morph (기본값)
컨트롤러 액션을 통해 전체 페이지를 다시 렌더링하고 차이점을 DOM에 병합합니다.
Selector Morph
# app/reflexes/example_reflex.rb
class ExampleReflex < ApplicationReflex
def update_metric
morph "#metric-display", render(partial: "metrics/metric", locals: { value: 42 })
end
end
Nothing Morph
클라이언트 DOM을 변경하지 않고 서버 측 로직만 실행합니다.
class ExampleReflex < ApplicationReflex
def background_task
LongRunningJob.perform_later
morph :nothing
end
end
수명 주기 메서드
서버 측 콜백
class ExampleReflex < ApplicationReflex
before_reflex :authenticate
around_reflex :measure_time
after_reflex :log_activity
end
클라이언트 측 일반 콜백
beforeReflex(element, reflex, noop, reflexId): WebSocket 요청 전송 전reflexSuccess(element, reflex, noop, reflexId): Reflex 실행 및 DOM 갱신 후reflexError(element, reflex, error, reflexId): 서버에서 처리되지 않은 오류 발생 시reflexHalted(element, reflex, noop, reflexId):throw :abort로 Reflex 중단 시afterReflex(element, reflex, noop, reflexId): 성공 및 실패 시 모두 실행finalizeReflex(element, reflex, noop, reflexId): 최종 정리 훅
DOM 이벤트
stimulus-reflex:beforestimulus-reflex:successstimulus-reflex:errorstimulus-reflex:haltedstimulus-reflex:afterstimulus-reflex:connectedstimulus-reflex:disconnectedstimulus-reflex:ready
실전 패턴
폼 처리
폼 요소 내부나 폼 요소에서 트리거된 Reflex는 입력값을 자동으로 직렬화하여 params에 전달합니다.
Promise 체이닝
this.stimulate('Comments#create')
.then(() => this.showSuccess())
.catch((err) => this.handleError(err))
영구 요소 (Permanent Elements)
data-reflex-permanent 속성을 지정한 요소는 전체 페이지 morph 시에도 상태가 보존됩니다.
<div data-reflex-permanent>
<video id="player" src="video.mp4" controls></video>
</div>