I have nested Stimulus controllers for a list and the nested list items. I am triggering an event based on clicking one of the list items, that I want run by my outer (list) controller, and in it I need access to the targets from the inner (list item) controller. In reading Having an outer controller that controls inner controller and some other posts, I figured out one way to identify the inner controller with:
`this.application.getControllerForElementAndIdentifier(event.currentTarget, “list-item”)’
But, it feels like I shouldn’t have to query the entire application when I already have the specific element. Is there a way to identify the specific Stimulus controller based on the element directly, vs. needing to use getControllerForElementAndIdentifier?
Thanks! That’s an interesting idea. It does seem that I can actually have only a list controller and not a list item controller that way, but there’s some duplication that I’m not sure about. I actually need to target a bunch of different elements from within the list item, so this works but feels inefficient:
// list_controller.js
export default class extends Controller {
trigger(event) {
const entryController = this.application.getControllerForElementAndIdentifier(event.currentTarget, "list-item");
const image = entryController.imageTarget
const heading = entryController.headingTarget
const text = entryController.textTarget
// Do some things with the image, heading, and text
}
}
Any thoughts about these different approaches, or if there’s another way I’m not thinking of? Thanks so much!