hotwired / stimulus

A modest JavaScript framework for the HTML you already have

Home Page:https://stimulus.hotwired.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

scoped outlets

intradayreview opened this issue · comments

I'm currently working on a UI that has multiple instances of the same Controller on the page. I'd like to use Outlets, but because they aren't scoped like Targets, I can't use them in this situation.

The parent Controller has context I'd like to pass to child Controllers.

It can be done using Targets like this for example.

<div data-controller="chart">
  <div data-controller="box" data-chart-target="box"></div>
  <div data-controller="box" data-chart-target="box"></div>
</div>
ChartController {
  boxTargetConnected(box) {
    const boxController = this.application.getControllerForElementAndIdentifier(
      box,
      "box"
    );

    boxController.chart = this;
  }
}
BoxController {
  connect() {
     console.log(this.chart)
  }
}

This seems to work from my test this morning, so my issue is solved, but it feels clunky now Stimulus has Outlets.

Maybe scoped Outlets could complete the bridge between a Target and an Outlet.

Something like this maybe?

<div data-controller="search" data-search-result-outlet="search->.result">
   <div class="result" data-controller="result">...</div>
</div>

Then when result Outlets are initialised they automatically get the context of the parent, this means they are scoped like Targets but with magic.

ResultController {
  connect() {
     console.log(this.searchController)
  }
}

This might be over reaching and complicating things, if so please delete.

Another solution is to use Stimulus Values on the parent and grab them when needed.

This will be the solution I go with and I'll close this ticket.