stimulus.js 사용기 - action(click event, global event like document, window.resize)



stimulus.js 를 사용해봤다. Rails 에서는 javascript 폴더 안에 controller 폴더를 만들고 xxxxx_controller.js 라는 js파일을 만들어 사용한다.

import {Controller} from "stimulus"

export default class extends Controller {
functionName(){
}
}

그 다음 위와 같이 js 파일을 구성하고 사용한다.

이제 이걸 사용하는 방법은 아래와 같이 사용한다. 아래에서의 gallery 는 위의 xxxxx이고 click은 trigger고, gallery#next 는 xxxxx_controller.js 에 정의해놓은 함수(위 사진에선 functionName같은)이다.

좀 더 쉽게 설명하면 클릭하면 xxxxx_controller 파일의 functionName() 함수를 호출해라와 같은 것이다.

<div data-controller="gallery">
  <button data-action="click->gallery#next"></button>
</div>

click이 아닌 "window의 크기가 변화하면, 문서가 준비되면" 같은 global event도 사용할 수 있다.

<div data-controller="gallery"
     data-action="resize@window->gallery#layout"></div>
위의 예제는 window의 크기가 resize되면 함수를 호출하는 것 아마 ready@document 와 같은 것도 되지 않을까 싶다.

라고 썼었는데 해보니 안됨 load@window 로 하면 됨 ... jQuery는 안되는건가... 아무튼 그럼.

다른 xxxx_controller.js 파일에 정의해놓은 함수를 불러와서 사용하고 싶다면 아래 링크를 참고하면 좋다. 써보려다 쓸 이유가 없어져서 안써봤다.

https://github.com/stimulusjs/stimulus/issues/94

참고 링크

https://github.com/stimulusjs/stimulus/blob/master/docs/reference/actions.md

https://discourse.stimulusjs.org/t/can-i-use-load-event/518/2

댓글

이 블로그의 인기 게시물

부트스트랩 사용 시 버튼 오른쪽 정렬하는 방법 (How to use float-right for right align in bootstrap)

맥(Mac)에서 MySql 사용 시 Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) 오류가 발생하는 경우 해결 방법

AWS Lambda + CloudWatch 를 이용해 주기적으로 AWS RDS 중지, 시작하는 방법(How to stop and start AWS RDS periodically using AWS Lambda + CloudWatch)