Stimulus: Cross-Controller Coordination With Events

Reading Time: 2 minutes

A controller is the basic organizational unit of a Stimulus application. They are instances of JavaScript classes that you define in your application. If you need controllers to communicate with each other, you should use events. Look at this to learn how.

 

Based on the DRY principle, sometimes we need to bind new elements to use an existing method or functionality across controllers. Stimulus offers a really easy way to do this.

For example:

app/javascript/controllers/home_controller.js:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [
    'homeLink',
  ]

  connect() {}

  openAlert() {
    alert('Test Message')
  }
}

app/views/home/index.html.erb:

<a href='#'
   data-controller='home'
   data-home-target='homeLink'
   data-action='click->home#openAlert'>Click me!</a>

Then, for this purpose, we are going to add a new page called test, and for that:

config/routes.rb

Rails.application.routes.draw do
  root 'home#index'
  get 'test', to: 'test#index'
end

app/javascript/controllers/test_controller.js:

import { Controller } from '@hotwired/stimulus'

export default class extends Controller {
  static targets = [
    'testLink',
  ]

  connect() {
  }

  openAlert(e) {
    alert('Test Message')
  }
}

app/views/test/index.html.erb:

<a href='#'
data-controller='test home'
data-test-target='testLink'
data-action='click->test#openAlert'>Click me test!</a>

Now to be able to call the openAlert method from home controller, instead of having the same method inside test controller, we need to do this:

app/views/test/index.html.erb::

<a href='#'
data-controller='test home'
data-test-target='testLink'
data-action='click->home#openAlert:test#openAlert'>Click me test!</a>


app/javascript/controllers/test_controller.js:
import { Controller } from &#039;@hotwired/stimulus&#039;

export default class extends Controller {
  static targets = [
    &#039;testLink&#039;,
  ]

connect() {}

openAlert(e) {
    this.dispatch(&#039;openAlert&#039;, e);
  }
}

This is a really good feature which will help you to keep track of your method calls and your code cleaner as well. Long story short, this is one of the features that Stimulus offers, and it will make your life just easier, but, what do you think of it?

0 Shares:
You May Also Like
Read More

Data Encryption with Rails 7

Reading Time: 4 minutes There are massive amounts of sensitive information managed and stored online in the cloud or connected servers. Encryption…