LoginSignup
1
1

はじめに

以下の記事で、Stimulus アプリケーションの起動時にしていることをまとめました。

起動時に、Router class、Dispatcher classのインスタンスを作成して、それぞれのインスタンスでstartメソッドを実行していることがわかりました。
しかし、それぞれのインスタンスの役割が何であって、なんのためにstartメソッドを実行しているのいまいちわかりませんでした。
調べた限り、それぞれの役割について書かれている記事は見当たりませんでした。
全てのコードを一気に読んで役割を推察するのは難しいです。
なので、少しずつコードを読み解いて、役割を理解していくことにします。
本記事では、それぞれのclassのプロパティを読み解きます。

Router classのプロパティ

以下は、Router classのプロパティです。

readonly application: Application
private modulesByIdentifier: Map<string, Module>
private scopesByIdentifier: Multimap<string, Scope>
private scopeObserver: ScopeObserver

applicationは、Stimulus アプリケーション自体です。

modulesByIdentifierModule classのインスタンスを値とするマップです。Module classの役割は、Stimulus controllerの管理です。1つのStimulus controllerに対して、1つのModule classのインスタンスが対応します。modulesByIdentifierのキーは、Stimulus controllerの識別子です。

scopesByIdentifierの型はMultimap<string, Scope> classという型ではありますが、要するにMap<string, Set<Scope>>のインスタンスです。Scope classは、Stimulus controllerが適用できる範囲を司るclassです。例えば、以下のようにStimulus controllerを指定しているとき、<div>要素とその子要素がこのcontrollerの適用範囲です。この範囲を司るのがScope classの役割です。

<div data-controller="modal">
  <button data-modal-target="button">閉じる</button>
</div>
<a href="#">戻る</a>

scopeObserverは、Scope classの全インスタンスの監視を管理するものです。つまり、Stimulus controllerを指定しているすべてのHTML要素の監視を管理しています。

Dispatcher classのプロパティ

以下は、Dispatcher classのプロパティです。

readonly application: Application
private eventListenerMaps: Map<EventTarget, Map<string, EventListener>>
private started: boolean

applicationは、Stimulus アプリケーション自体です。

eventListenerMapsは、イベントを監視するDOMとイベントリスナーを管理するためのものです。

startedは、イベントリスナーを設置済みか否かを判別するためのものです。

おわりに

本記事では、Router class、Dispatcher classのプロパティを読み解きました。その結果、それぞれのclassの役割がなんとなくわかってきました。おそらく、以下のような感じだと思います。

  • Router: Stimulus controllerを管理し、それが適用されているDOMを監視する
  • Dispatcher: Stimulus controllerが適用されているDOM内のイベントに対して、Stimulus controllerのActionを実行させる

なんとなく役割はわかってきたのですが、いまいち全貌がわかりません。なので、今後はclass同士の依存関係を明らかにして、役割の輪郭をはっきりさせようと思います。

1
1
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
1