htmx icon indicating copy to clipboard operation
htmx copied to clipboard

[1.9.10] WebSockets: handling events with `hx-on` seems broken

Open haja opened this issue 2 years ago • 1 comments

Hi,

The behaviour of websocket-extension with hx-on is a bit counter-intuitive in my opinion. Connecting and receiving updates via the websocket works flawlessly, but registering events via hx-on on a child element of the hs-ext="ws"-element does not seem to work:

<!-- not wokring -->
<div id="htmx-livedata" hx-ext="ws" ws-connect="/ws/client">
  <div hx-on:htmx:ws-connecting="console.log('websocket connecting', event)">
    event-holder
  </div>
</div>

The events are received via global handler, though, so this works as expected:

<!-- end of body, working example -->
<script>
document.body.addEventListener('htmx:ws-connecting', function (evt) {
    console.log(evt);
})
</script>

And registering on the ws element directly seems to work for consecutive connects, but not on the inital page laod:

<!-- this work on reconnects -->
<div hx-ext="ws" ws-connect="/ws/client" hx-on:htmx:ws-connecting="console.log('websocket connecting', event)">
  event-holder
</div>

Is this a known issue? I haven't found any hints on such limitation in the docs (neither hx-on nor ws-ext).

haja avatar Dec 26 '23 10:12 haja

I've also just experienced this. There's some kind of timing issue: if hx-on (e.g., hx-on:htmx:ws-open is on an element contained inside an element that has the ws-connect, the connect completes before the handler is registered. If the hx-on is on the same element, then it gets registered in time and sees the wsOpen event.

tedyoung avatar May 23 '24 23:05 tedyoung