stimulusreflex / stimulus_reflex

Build reactive applications with the Rails tooling you already know and love.
https://docs.stimulusreflex.com
MIT License
2.28k stars 172 forks source link

routing reflexes to controllers #97

Closed leastbad closed 4 years ago

leastbad commented 4 years ago

Recently I have been intensely focused on building a series of increasingly more sophisticated example StimulusReflex applications (hopefully) destined for the Expo site. Aside from (hopefully) being instructive and fun to make, it's very important for library builders to play the role of end-users and dogfood everything on a regular basis. Sometimes you surface issues in the mouthfeel of the API.

One of the most powerful recent additions to StimulusReflex is the callback system. @hopsoft and I worked very hard to make everything behave in a rational, predictable manner even while behind the scenes some aspects of this goal were tricky to implement.

The problem I keep running into starts with good intentions. I'll be designing an interface that has multiple widgets in play, and instead of wrapping the whole body in a giant Stimulus controller, I'll put data-controller on the parent elements of the appropriate widgets.

Here's the thing: if a data-reflex occurs inside of the child hierarchy of the parent element that has the data-controller attribute, you have the opportunity to write callbacks which fire when those reflex events are triggered. But if you want to put a data-reflex for a controller elsewhere on your interface, StimulusReflex doesn't currently have any mechanism for firing callbacks.

What I've found, as a library user, is that first I'll spend time trying to find an elegant solution; then I'll end up with two separate controllers that, over time, gain more and more identical functionality; finally, I'll just move the controller to the highest point of the DOM I can access and consolidate the code into one controller. I've now created a single working (yay) controller that is likely to only work on a single interface (sigh), instead of two relatively flexible controllers that I can reuse on many pages.

I'm wondering if there's a way that we could opt-in to callbacks even if we're not under the hierarchy of the data-controller by pointing to an element via a CSS selector. For example:

<div id="example" data-controller="example">
  <button data-reflex="click->ExampleReflex#no_problem">No Problem!</button>
</div>

<button data-reflex="click->ExampleReflex#hear_me" data-reflex-controller="#example">I'm a real boy!</button>
leastbad commented 4 years ago

Closing because nobody has clamoured for this functionality, and it would significantly complicate how callbacks are implemented.