kccarter
Improving LiveView JS interop to reduce the need for Hooks just to register for DOM events
This is likely a feature request unless we’re overlooking something, but it would be a nice improvement to the developer experience if there were LiveView Bindings for calling a Javascript function when a DOM event fires.
The existing Bindings offer phx-click for sending messages to the server, but not for calling local Javascript. phx-mounted is the closest binding, but then you have to define a bunch of Hooks just to register for regular DOM events.
The small set of JS Commands is helpful, but doesn’t allow us to call arbitrary functions.
Something like:
<div phx-click={JS.call(myJavascriptFunction(evt)}></div>
Most times, we just want an onClick, onInput or onChange handler to call some local JavaScript without any round trips to the server. So extending the Bindings to include phx-on... would be equally helpful.
Or perhaps:
<div phx-onInput={JS.call(...)}></div>
<div phx-onEvent={'input', JS.call(...)}></div>
The Client Hooks via phx-hook section explains exactly how to do what we want, but we’re curious if there’s an appetite for trying to improve this so that we don’t have to write all the Hook functions.
Most Liked
chrismccord
# // app.js
# window.addEventListener("js:call", e => window[e.detail.name](...e.detail.args))
#
# heex
# <button phx-click={js_call("alert", ["clicked!"])}>Click me</button>
#
def js_call(name, args \\ []) do
JS.dispatch("js:call", detail: %{name: name, args: args})
end
LostKobrakai
You can do that already using Phoenix.LiveView.JS — Phoenix LiveView v1.2.5.
sodapopcan
I feel the docs are a bit confusing. When given a client-side JS command, phx-click will not send any request to the server. Eg, phx-click={JS.show()}. However if you read the Bindings sections shared by @kccarter, you might think this is the case. Even when you know about JS commands, it’s still confusing wording. I can bring it up in the issue tracker unless someone thinks I’m really off-base here.
Popular in Proposals: Ideas
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









