Stimulus Discourse

Having an outer controller that controls inner controller

I have a tabbed interface (I use the tabbed interface controller example provided)
On each of my tabs I have charts though. I would like that when the tabs shows up, the charts render at the same time.
I am guessing that I need to have my tabs controller call my smaller charts element controller. I’m not sure if it’s a good idea to call a controller from another one.

Anybody has an idea of what is best to do here ?

00

We right now have this thing. Connection method in our ApplicationController wrapper. I already posted it in common patterns:

  /**
   * Get instance of remote controller
   * @param controller - controller name
   * @param id - instance element ID
   */
  connectRemote(controller, id = null) {
    const elementId = id || controller
    const element = document.getElementById(elementId)
    return this.application.getControllerForElementAndIdentifier(element, controller)
  }

This case you can fire action on tab content controller via tab button for example.
Adrien showed another example. Please feel free what you like here:

I think it’s no issues to call another controller inside a controller. We don’t build super-duper-reusable single responsibility components, we solving a real problem on the specific page.
At least this is my point when I use Stimulus :slight_smile:

2 Likes

How about firing a custom event on the target and then adding an event handler in the target controller. Something like adding this

this.panelTarget.dispatchEvent(new Event('update'))

into the parent controller

and then in the controller associated with the panel have something like this

update() {
    ... /* add your update logic here */
  }

in the child controller. With this as an attribute

data-action="update->trades-tab#update"

(just a thought, I’m not sure how I feel about each)

2 Likes

Using custom event was one of the recommendations of Sam in an earlier discussion on Github

1 Like

How would you pass extra data along with the custom event?

I’ve tried: .dispatchEvent(new Event('update', data)), but it doesn’t seem to be sent…

using CustomEvent does work for me to pass additionnal data through the event .dispatchEvent(new CustomEvent('update', { detail: data }))

1 Like

Ah nice, thanks! :slight_smile: I didn’t know about CustomEvent.