defp publish(js \\ %JS{}) do
IO.inspect(js, label: "JS")
js
|> JS.set_attribute({"value", "publish"}, to: "#new_planner_action")
|> JS.dispatch("click", to: "#publish_button")
end
My big question is, why is that I’m getting this, on my terminal when the liveview reloads?
because you’re calling the function in your template. phx-click={publish()} is placing the output of the execution of the publish function as the value of the phx-click attribute. Most likely not what you want.
And when I click the button, nothing happens.
you should pass the name of the event to phx-click, and then handle the event in a handle_event callback in your view. Like here: Bindings — Phoenix LiveView v0.17.6
I’m not calling the function on my template… im telling to call the function when there is a phx-click. That’s straight from liveview documentation, on Bindings — Phoenix LiveView v0.17.6
alias Phoenix.LiveView.JS
def hide_modal(js \\ %JS{}, selector) do
js
|> JS.push("modal-closed")
|> JS.remove_class("show", to: selector, transition: "fade-out")
end
The function is indeed called on render, this is why you see the result of IO.inspect. Nothing wrong with that, it is the expected usage.
The docs does not tell that the function is not called. It’s just that the phx-click accepts a JS struct as value and this is what the functions (from the doc and yours) return.
It is called because you have {publish()} which is a function call, as @trisolaran said. So on render the function is called, calls IO.inspect, and then returns a JS struct that is serialized in the phx-click attribute.
To maybe make this a bit more clear: publish/0 constructs a command and is called at the time the template needs to know the command. The function is not called or executed when the returned command is executed by the javascript side.