Events
Communication between Django, HTMX, and AlpineJS.
Workflow: Triggering client-side events from Django
In django view, add the HX-Trigger header to the HttpResponse.
Set the header value to the name of your custom event: response[“HX-Trigger”] = “entity-updated”.
Listen for this event in AlpineJS using @entity-updated.window=”handleUpdate()”.
Workflow: Communicating between AlpineJS components
Use $dispatch(‘event-name’, { data: ‘value’ }) within an AlpineJS function.
Ensure the event bubbles if the listener is a parent or sibling.
Catch the data in the receiving component with @event-name.window=”myData = $event.detail.data”.
Workflow: Handling HTMX lifecycle hooks
Identify the specific phase (e.g., @htmx:after-request or @htmx:before-swap).
Attach an AlpineJS listener to the element making the request:
<button hx-get="{% url 'data-endpoint' %}" @htmx:after-request="console.log('Status:', event.detail.xhr.status)"> Check Status </button>
Properties: Event Scoping
.window: Listens on the global window object..document: Listens on the document level..stop: Prevents the event from bubbling further.