I have a question about the Phoenix LiveView Component (v0.15.4).
In the documentation, there is an example code:
def handle_info({:updated_card, card}, socket) do
send_update CardComponent, id: card.id, board_id: socket.assigns.id
{:noreply, socket}
end
LiveView components do not have a handle_info/2
callback, so send_update/3
is called to redirect events from the parent LiveView to a specific component.
However, I want to send events directly from the parent LiveView to the specific component, because I want to do something like this
# parent LiveView
def handle_info({:new_card, card_id}, socket) do
send_event CardStackComponent, id: :card_stack, event: "add_card", params: %{"card_id" => card_id}
{:noreply, socket}
end
# component
def handle_event("add_card", %{"card_id" => card_id} = _params, socket) do
card = get_card(card_id)
socket =
update(socket, :cards, fn cards ->)
[card | cards]
end)
{:noreply, socket}
end
Of course, there is no such function as Phoenix.LiveView.send_event/2
. The above is a fictional code to illustrate my intention.
I know how to send events from a client (browser) to a specific component, either by adding the phx-target="<%= @myself %>"
attribute to an HTML element, or by using the pushEventTo
method in a JavaScript program.
However, as far as I know, there is no way to send an event directly from a parent LiveView to a specific component.
Is there any workaround or better way?