Stimulus Outlets API

Episode #378 by Teacher's Avatar David Kimura

Summary

Outlets let you reference Stimulus controller instances and their controller element from within another Stimulus Controller by using CSS selectors. In this episode, we look at a simple example and then refactoring some older code where we used some workarounds to communicate with other stimulus controllers.
rails stimulusjs javascript 13:57

Chapters

  • Introduction (0:00)
  • Episode Preview (0:12)
  • Development Start (1:35)
  • Stimulus Controllers (2:21)
  • Outlets API (3:54)
  • Demo (5:57)
  • Refactor Episode 337 (7:35)
  • Demo (11:33)
  • Warning on Outlet names (12:11)
  • Final Thoughts (13:20)

Resources

Download Source Code

Summary

# Terminal
bin/rails g stimulus alert
bin/rails g stimulus something

# app/javascript/controllers/alert_controller.js
import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="alert"
export default class extends Controller {
  connect() {
  }

  alert(message) {
    alert(message)
  }
}

# app/javascript/controllers/something_controller.js
import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="something"
export default class extends Controller {
  static outlets = ["alert"]

  connect() {
  }

  clicked() {
    if (this.hasAlertOutlet) {
      this.alertOutlet.alert("something clicked")
      // this.alertOutlets.forEach( alert => alert.alert("something") )
    }
  }
}

# views/welcome/index.html.erb
<div data-controller="alert" class="message"></div>

<div data-controller="something" data-something-alert-outlet=".message">
  <%= button_tag "click me", "data-action": "something#clicked" %>
</div>