Can I push an event to the server from a JS.dispatch() event handler?

Hmm, only one element with phx-hook would be necessary. That hook would define a mounted lifecycle callback that sets up all the window.addEventListener aka JS.dispatch event handlers that need to push an event to the server.

Not ideal and a bit roundabout, but if consolidating all the JS.dispatch event handlers is not workable, those event handlers could instead emit a relay event with the processed output as a payload to a generic relayer/hidden element as discussed here: DeadView => LiveView interaction?.

And skimming through the live_socket.js, the closest public method available would be liveSocket.execJS. It’s supposed to be used in conjunction with data attributes that embeds JS commands, but it may be possible to use directly.

If you desire, you can also integrate this functionality with Phoenix’ JS commands, executing JS commands for the given element whenever highlight is triggered. First, update the element to embed the JS command into a data attribute:

<div id={"item-#{item.id}"} class="item" data-highlight={JS.transition("highlight")}>
  <%= item.title %>
</div>

Now, in the event listener, use LiveSocket.execJS to trigger all JS commands in the new attribute:

let liveSocket = new LiveSocket(...)
window.addEventListener(`phx:highlight`, (e) => {
  document.querySelectorAll(`[data-highlight]`).forEach(el => {
    if(el.id == e.detail.id){
      liveSocket.execJS(el, el.getAttribute("data-highlight"))
    }
  })
})

source: JavaScript interoperability — Phoenix LiveView v0.20.2