When using HTMX is a common pattern to write event based actions or ui updates in the client side. It’s a good practice to use javascript as event based scripting system in our client side code. Some events from the server might be required in client side to update the DOM or to trigger some actions.
A common pattern to achieve this is to respond a header Server-Event
with a value holding the custom event and then using javascript, you can handle the custom event.
eg:
// trigger a custom event
document.dispatchEvent(new CustomEvent('my-custom-event', { detail: { message: 'Hello World' } }));
// handle the custom event
document.addEventListener('my-custom-event', function (e) {
console.log('my-custom-event', e.detail.message);
});
In htmx world, we might require a ui block to send http request to update the content of the block when scenarios like, a new data list is updated.
Example:
- By using
hx-trigger
attribute, we can signal a block to send a get request to update the content when alist-updated
event is dispatched.
<div hx-get="/get-updated-list" hx-trigger="list-updated">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
- From an endpoint that handles some action in the server, we can respond with a
Hx-Trigger
header to trigger the event in the client side.
func handleSomeAction(w http.ResponseWriter, r *http.Request) {
// some action
w.Header().Set("Hx-Trigger", "list-updated")
w.Write([]byte("Some action completed"))
}
- This will trigger the
list-updated
event in the client side and the block will send the get request to/get-updated-list
and replace the content with the response.
It’s a very useful pattern to achieve async updates in the client side, without relying on oob
attributes, which will select and replace multiple blocks in the client side.