hx-trigger response header
Hi guys,
i was trying to trigger multiple events via the HX-Trigger response header. Reading the docs and looking at the code i know i can trigger either by comma separated list like so event1, event2, ... or have a json object with the event names as root level properties like so {"event1": "foo", "event2": {"myDetail": "bar"}}
My Problem is that this means I have to keep track of the hx-trigger response headers set in my application. If I want to trigger multiple events and one of them wants to use extended json details I'll have to merge all the events into one json object. I can not just set multiple hx-trigger headers, since they will be concatenated and separated by comma (,) as stated in (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getResponseHeader).
A possible solution would be to always split the header at comma taking into account that the comma must not be enclosed by curly braces. Similarly to how it is already done for the "no json" case. the resulting array then could be handled one item at a time parsing json if applicable.
I could draw up a pr if wanted.
Cheers!
This seems like something that can be done easily in the backend if you expect this case in your application. Just create an empty object {} and each time your backend logic needs to add a hx-trigger just add/set the event you want property in this object with either the trivial case or the detailed one depending on the trigger you need. Then at the end of your request logic add the line to send this object as the trigger header but make it conditional on the trigger object not being an empty object {}
Hi Michael, thanks for your reply! Depending on the backend infrastructure and the actual application design this can be somewhat of an annoyance to pass around this object / make it accessible. But actually my point is not so much about how to achieve this in backend since that's naturally out of scope for htmx. combining headers with the same name by comma separating them is in the http spec if I'm not mistaken and this is also how the used XMLHttpRequest.getResponseHeader is handling this. Also the proposed change is entirely backwards compatible.