Best way to push event with data from javascript

On a button click I want to run a JS-function to collect some data and send that to liveview. This is what I came up with…
Is there a better way?

  phx-click={JS.dispatch("my-trigger-push-event", [])}>
function gather_data() {...}
Hooks.MyPushEventHook = {
    window.addEventListener("my-trigger-push-event", e => {
      this.pushEvent("from-my-trigger-push-event", gather_data())

No hook and JS.push instead of JS.dispatch?

push accept a map of values to send to the server as a payload.

The value for JS.push has to come from a JS-function (changed the example to make that more clear)

I can’t do that:

<button phx-click={JS.push("clicked", value: javascript_function())}>click me!</button>

Oh, I see, maybe you can still get rid of the hook and set up the EventListener outside of it before any hooks, unless your gather_data() function depends on the element, in this case I think that the Hook will be less messy since you have easy access to the element from the Hook, but since you are putting the hook straight into the button I don’t think that this is the case.

1 Like

Yes I had that before, and got into trouble with all the free-flying javascript. (I’m just learning JS after (ab)using it for decades). So I thought to let Phoenix help me keep it contained.

It’s a little hard for me to tell where to put what, especially where is the right boundary between liveview and JS. For the control I’m trying to build, it would be easier for me to just let LV handle everything, but it seems just wrong to let the server handle pure UI stuff.

1 Like