Skip to content

Commit

Permalink
Add doc examples using attach_hook for code organization instead of L…
Browse files Browse the repository at this point in the history
…iveComponents (#3685)

* Update attach_hook/4 with extract handle_event example

* Add small header for doc linking

* Clarify the code-organization sections of the Welcome guide

Add small hierarchy headers to the "Compartmentalize state,
markup, and events" section

Use the guidance in "Functional components or live components?"
at the top of `Phoenix.LiveComponent` to avoid using LiveComponents
only for organization

Provide longer example with a few different alternatives of
what *can* be used for organizing events

* Remove suggested option to delegate events manually

As pointed out, sticking with attach_hook keeps ownership of
the event in the new component

* Remove Helpers and use more-standard {:ok, socket} style

* Add forgotten line break

* Remove 2nd attach_hook example and link directly to the first

* Update lib/phoenix_live_view.ex

* Update guides/introduction/welcome.md

* Update guides/introduction/welcome.md

* Update guides/introduction/welcome.md

* Update guides/introduction/welcome.md

* Update guides/introduction/welcome.md

* Update guides/introduction/welcome.md

* Update guides/introduction/welcome.md

* Reverse locations of long-code-example & link-to-that-example

Now the "using attach_hook/4 to extract handle_events" example
code is actually kept in the doc FOR attach_hook

This keeps the welcome.md page similar to it's original size

* Rename "Organizing code" section -> "Sharing event handling logic"

* Continue minimizing changes to welcome.md

- Merge the "attach_hook/4 to organize event handling" section into
the "Function components" one above it

- Return to the previous bullet-point based summary, adding only a single
line to emphasize that function components can work alone for markup, but
also organize event handling when paired with attach_hook/4

* Apply suggestions from code review

* Apply suggestions from code review

---------

Co-authored-by: Gary Rennie <[email protected]>
Co-authored-by: Steffen Deusch <[email protected]>
Co-authored-by: José Valim <[email protected]>
  • Loading branch information
4 people authored Feb 23, 2025
1 parent ea2c6f0 commit 573141b
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 7 deletions.
25 changes: 19 additions & 6 deletions guides/introduction/welcome.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,8 @@ For authentication, with built-in LiveView support, run `mix phx.gen.auth Accoun
LiveView supports two extension mechanisms: function components, provided by
`HEEx` templates, and stateful components, known as LiveComponents.

### Function components to organize markup and event handling

Similar to `render(assigns)` in our LiveView, a function component is any
function that receives an assigns map and returns a `~H` template. For example:

Expand All @@ -245,9 +247,16 @@ You can learn more about function components in the `Phoenix.Component`
module. At the end of the day, they are a useful mechanism for code organization
and to reuse markup in your LiveViews.

However, sometimes you need to share more than just markup across LiveViews,
and you also need to move events to a separate module. For these cases, LiveView
provide `Phoenix.LiveComponent`, which are rendered using
Sometimes you need to share more than just markup across LiveViews. When you also
want to move events to a separate module, or use the same event handler in multiple
places, function components can be paired with
[`Phoenix.LiveView.attach_hook/4`](`Phoenix.LiveView.attach_hook/4#sharing-event-handling-logic`).

### Live components to encapsulate additional state

A component will occasionally need control over not only its own events,
but also its own separate state. For these cases, LiveView
provides `Phoenix.LiveComponent`, which are rendered using
[`live_component/1`](`Phoenix.Component.live_component/1`):

```heex
Expand All @@ -261,6 +270,11 @@ are more complex than function components themselves. Given they all run in the
same process, errors in components cause the whole view to fail to render.
For a complete rundown, see `Phoenix.LiveComponent`.

When in doubt over [Functional components or live components?](`Phoenix.LiveComponent#functional-components-or-live-components`), default to the former.
Rely on the latter only when you need the additional state.

### live_render/3 to encapsulate state (with error isolation)

Finally, if you want complete isolation between parts of a LiveView, you can
always render a LiveView inside another LiveView by calling
[`live_render/3`](`Phoenix.Component.live_render/3`). This child LiveView
Expand All @@ -277,9 +291,8 @@ Given that it runs in its own process, a nested LiveView is an excellent tool
for creating completely isolated UI elements, but it is a slightly expensive
abstraction if all you want is to compartmentalize markup or events (or both).

To sum it up:

* use `Phoenix.Component` for code organization and reusing markup
### Summary
* use `Phoenix.Component` for code organization and reusing markup (optionally with [`attach_hook/4`](`Phoenix.LiveView.attach_hook/4#sharing-event-handling-logic`) for event handling reuse)
* use `Phoenix.LiveComponent` for sharing state, markup, and events between LiveViews
* use nested `Phoenix.LiveView` to compartmentalize state, markup, and events (with error isolation)

Expand Down
72 changes: 71 additions & 1 deletion lib/phoenix_live_view.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1508,7 +1508,77 @@ defmodule Phoenix.LiveView do
interoperability](js-interop.html#client-hooks-via-phx-hook) because a client hook
can push an event and receive a reply.
## Examples
## Sharing event handling logic
Lifecycle hooks are an excellent way to extract related events out of the parent LiveView and
into separate modules without resorting unnecessarily to LiveComponents for organization.
defmodule DemoLive do
use Phoenix.LiveView
def render(assigns) do
~H\"""
<div>
<div>
Counter: {@counter}
<button phx-click="inc">+</button>
</div>
<MySortComponent.display lists={[first_list: @first_list, second_list: @second_list]} />
</div>
\"""
end
def mount(_params, _session, socket) do
first_list = for(i <- 1..9, do: "First List \#{i}") |> Enum.shuffle()
second_list = for(i <- 1..9, do: "Second List \#{i}") |> Enum.shuffle()
socket =
socket
|> assign(:counter, 0)
|> assign(first_list: first_list)
|> assign(second_list: second_list)
|> attach_hook(:sort, :handle_event, &MySortComponent.hooked_event/3) # 2) Delegated events
{:ok, socket}
end
# 1) Normal event
def handle_event("inc", _params, socket) do
{:noreply, update(socket, :counter, &(&1 + 1))}
end
end
defmodule MySortComponent do
use Phoenix.Component
def display(assigns) do
~H\"""
<div :for={{key, list} <- @lists}>
<ul><li :for={item <- list}>{item}</li></ul>
<button phx-click="shuffle" phx-value-list={key}>Shuffle</button>
<button phx-click="sort" phx-value-list={key}>Sort</button>
</div>
\"""
end
def hooked_event("shuffle", %{"list" => key}, socket) do
key = String.to_existing_atom(key)
shuffled = Enum.shuffle(socket.assigns[key])
{:halt, assign(socket, key, shuffled)}
end
def hooked_event("sort", %{"list" => key}, socket) do
key = String.to_existing_atom(key)
sorted = Enum.sort(socket.assigns[key])
{:halt, assign(socket, key, sorted)}
end
def hooked_event(_event, _params, socket), do: {:cont, socket}
end
## Other examples
Attaching and detaching a hook:
Expand Down

0 comments on commit 573141b

Please sign in to comment.