wimdeblauwe / htmx-spring-boot

Spring Boot and Thymeleaf helpers for working with htmx
Apache License 2.0
436 stars 41 forks source link

Support returning multiple HX Trigger events #18

Closed checketts closed 2 years ago

checketts commented 2 years ago

As I've begun using HTMX I've had some cases when I could choose to return multiple events, so I investigated the API. The following HX-Trigger headers could be set:

HX-Trigger: myEvent
HX-Trigger: {"myEvent": "my details"}
HX-Trigger: {"myEvent": "my details", "myEvent2": "my details"}

(along with the after-settle and after swap options)

To encapsulate these details I want to create an HtmxResponse object (combining @odrotbohm's HtmxPartials) with an api of:

htmxReponse.addTrigger("myEvent");
htmxReponse.addTrigger("myEvent", HxTriggerLifecycle.SWAP);
htmxReponse.addTrigger("myEvent", "myDetails");
htmxReponse.addTrigger("myEvent", "myDetails", HxTriggerLifecycle.SWAP);

Alternatively we could use a builder style, but I'm not sure if it offers much benefit:

htmxReponse.addTrigger("myEvent");
htmxReponse.addTrigger(new HxTriggerBuilder("myEvent").withDetails("myDetails").withLifeCycle(SWAP));

The shortest trigger option will be the most common (no details and the RECEIVE lifecycle)

That way users don't need to generate the json. I don't think we need to support all these options in the annotation.

wimdeblauwe commented 2 years ago

Interesting, did not know you can add multiple events. Could you elaborate when this is useful?

We could support this on the annotation as well I think?

checketts commented 2 years ago

More events come into play if we are trying to do fine-grained UI updates. This is a contrived example, but imagine if a user was editing their preferences and the form let them change their display name and avatar. We might emit a user:name and user:avatar event on that response to trigger updates on the page.

Interestingly, oob updates and events are 2 different solutions that help with these secondary updates. I've been trying explore when each is appropriate.

checketts commented 2 years ago

Closed by #21