I have a form with two Datetimepickers representing a datetime-range (initialized by the same Stimulus controller) and a few buttons to quickly select times for them. This involves getting the Controller instance of each Datetimepicker and setting the appropriate time for each.
There are multiple possibilities to achieve this:
- Wrap the “quickselect” Controller around the buttons and the datetimepickers, then define each datetimepicker as target. In the #setTime-Action, read the
data-startanddata-endattributes from theevent.targetand apply them to the datetimepickers. This involves reading the data-Attributes manually (i.e. they have no Stimulus value-accessors).- Pros: Each datetimepicker target is distinct
- Cons: Start and End times are not explicitly declared as values, Datetimepicker-Controller-Instances must be retrieved by
Stimulus.getControllerForElementAndIdentifier, Datetimepicker-Elements are “tightly coupled” to Quickselect, as they must declare themselves as targets.
<div data-controller="quickselect">
<button data-action="quickselect#setTime" data-start="08:00" data-end="12:00">...</button>
<button data-action="quickselect#setTime" data-start="12:00" data-end="16:00">...</button>
<input data-controller="datetimepicker" data-quickselect-target="start">
<input data-controller="datetimepicker" data-quickselect-target="end">
</div>
- Create a “quickselect” instance for each button, then define the datetimepickers as outlets so the Controller instances of the Datetimepickers can be accessed instantly.
- Pros:
startandendcan be defined as Stimulus values. Datetimepicker-Controller-Instances can be accessed instantly. - Cons: Repitition-heavy, outlets are distinguished by Controller identifier => there is no clear distinction between the instances of
startandendaside from manual checks.
- Pros:
<button data-controller="quickselect" data-action="quickselect#setTime" data-quickselect-start-value="08:00" data-quickselect-end-value="12:00" data-quickselect-datetimepicker-outlet="#start,#end">...</button>
<button data-controller="quickselect" data-action="quickselect#setTime" data-quickselect-start-value="12:00" data-quickselect-end-value="16:00" data-quickselect-datetimepicker-outlet="#start,#end">...</button>
<input data-controller="datetimepicker">
<input data-controller="datetimepicker">
Is there a recommended way of doing this? What are the considerations? I think I prefer the second variant, it is pretty clear from the markup what happens and having explicit Stimulus values leaves no ambiguity as to where the values are used.