Stimulus Discourse

Getting parent controller from within child

I’ve seen some discussion on how to best get a parent controller from within a child controller. I will outline my current solution here and if others find it useful, I will look at adding ‘getParentControllerForIdentifier’ via a pull request.

  getParentControllerForIdentifier(identifier) {
    return this.application.controllers.find(controller => {
      return (
        controller.context.identifier === identifier &&
        controller.element.contains(this.element)
      )
    })
  }

I like that idea in theory, but there could be many parent controllers up the tree with the same identifier, so it might be better to change it to getNearestParent…etc and ensure the code gets only the controller for the parent element closest to the child.

Good point. As there are many potential controllers, I wonder what’s the most efficient way of getting the closest parent?

There is already the undocumented function getControllerForElementAndIdentifier that you can use

some references:


This post was flagged by the community and is temporarily hidden.

This post was flagged by the community and is temporarily hidden.

I can offer a compelling solution that does not require access to the application object eg. can be called from outside of a Stimulus controller if necessary.

First, modify your controllers so that in the connect() method you add this line:

this.element[this.identifier] = this

This means that each controller - including your “parent” - will expose their internal state via a variable attached to it’s DOM element.

Now, accessing the widget controller of your parent is a query away:

this.element.closest('[data-controller~=widget]').widget