1
0

stimulus で複数の同一 action の指定

Posted at

はじめに

本記事はStimulusを参考にしています。
勉強中のため、誤りやもっといいやり方があるかも知れません。
その場合は、ご指摘いただけますと幸いです。

また、可能な限りわかりやすく記載するつもりですが、不明瞭な点、追記した方がいい点などがございましたら、合わせてご教授ください。

この記事の目的

恥ずかしながら、英語が得意なわけではないので、探すのに時間がかかったので、書き残そうと思った次第です。
同一のDOMイベントに対し、複数のアクションが書きたかったのですが、data-controller、および data-target の指定方法がわからなかったので、やり方を記します。

今回は、form に対して、data-controller を指定するやり方で備忘録を残します。

パーシャルの記載

input 要素に対して、変更が行われた場合、hoge-hogefoo が呼び出されます。
呼び出し順序は、左から右に呼び出されます。

= simple_form_for(hoge, url: hoge_path(hoge), html: {data: { controller: "hoge-hoge foo" } }  do |f|

    = f.input :hoge_id,
      label: 'サンプル',
      input_html: {data: { action: "change->hoge-hoge#replace change->foo#update", "hoge-hoge-target": "hogeHoge", "foo-target": "foo"}}

controller の記載

特別な書き方をする必要はありません。

// controllers/hoge_hoge_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "hogeHoge" ]

  replace() {
    // 処理を記載する
  }
}
// controllers/foo_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "foo" ]

  update() {
    // 処理を記載する
  }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0