borisgoro
Can I push an event to the server from a JS.dispatch() event handler?
Is there a way to push an event to the server from an event handler invoked via JS.dispatch()? pushEvent seems to be unavailable. Example code:
app.js
window.addEventListener("phx:custom_event", (event) => {
// ...
// some code
// ...
liveSocket.pushEvent(...) // doesn't work
})
Most Liked
codeanpeace
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.
https://github.com/phoenixframework/phoenix_live_view/blob/main/assets/js/phoenix_live_view/live_socket.js#L237-L239
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.execJSto 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 v1.2.5
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









