How to communicate between two instance of the same controller?

Alright, hear me out. I am trying to communicate with different instances of the same controller using custom events. The problem is, when I dispatch an event, only the instance that dispatched it gets it back. Is there any way to communicate between two instances of the same controller?

Here is the .erbfile

<div id="<%= dom_id todo %>">
  <div>
    <input type="checkbox" class="inline" data-id="<%= todo.id %>"
           data-controller="nestable-select"
           data-action="change->nestable-select#onChange nestable-select:changed->nestable-select#customChange"
      />
    <div class="inline"><%= todo.title %></div>
  </div>
  <div class="ml-6">
    <% todo.children.each do |todo| %>
      <%= render partial: "sprints/todos/todo", :locals => { todo: todo} %>
    <% end %>
  </div>
</div>

This is the stimulus controller

import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="nestable-select"
export default class extends Controller {
  connect() {
    console.log(`Instance of ${this.element.dataset.id}`);
  }

  onChange() {
    this.dispatch('changed', { detail: { sourceId: this.element.dataset.id }});
  }

  customChange(event) {
    console.log(event);
    console.log(`Hi there, this is ${this.element.dataset.id}, I got this event ${event}`)
  }
}

and here is the screenshot of the console.

Hi there.

Sorry for generic replay, but have you tried Outlets?

2 Likes

I haven’t tried it yet. Another solution I tried was to move the controller up the DOM tree and manage all the elements from there.

I will give Outlets a try as well.

Thanks.