This is Part 2 of Party mode! Hotwired Stimulus 101
After implementing the Party Mode with Ctrl+B, I realized that most keyboards in mobile phones do not have a Ctrl button.
How can I add a trigger for those browsing via a mobile browser?
I decided to reuse the search feature. When a specific keyword is entered, it is equivalent to pressing Ctrl+B. But the search feature is already bound with an existing Stimulus controller, how do we connect it with our party controller with minimum changes?
Cross-controller communication via Outlet
The behavior that I need can be done using a Stimulus outlet. It allows cross-controller communication, including accessing a method defined in another controller. In our case, we want to access the partyMode() method when a specific keyword is entered.
1) Add a "party" class to the DOM that hosts my party component. This class will be used as the identifier of the outlet.
<header data-controller="party" class="party">
</header>
2) Next, an outlet with "party" class is added to the DOM that hosts the search component.
<div data-controller="search" data-search-party-outlet=".party">
</div>
3) Next, in my search controller, an outlet named "party" is defined.
static outlets = [ "party"]
4) Now I can access the method I need from the search controller.
if (keyword.toLowerCase() === 'neon') {
this.closeSearch()
this.partyOutlet.partyMode() // This method is from party controller
}