Hotwired Stimulus 101 (Part 2)

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
}

 


AI Summary
gpt-4o-2024-05-13 2024-07-15 22:14:54
In Part 2 of "Hotwired Stimulus 101," the author addresses adding a Party Mode trigger for mobile users who lack a Ctrl button. By using Stimulus outlets for cross-controller communication, they implement a solution where entering a specific keyword in the search field triggers the party mode.
Chrome On-device AI 2025-02-08 10:57:29

Share Article