Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add doc examples using attach_hook for code organization instead of LiveComponents #3685

Merged
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
af1fc87
Update attach_hook/4 with extract handle_event example
ericridgeway Feb 20, 2025
41038ce
Add small header for doc linking
ericridgeway Feb 20, 2025
9725609
Clarify the code-organization sections of the Welcome guide
ericridgeway Feb 20, 2025
03665c0
Remove suggested option to delegate events manually
ericridgeway Feb 20, 2025
5007d54
Remove Helpers and use more-standard {:ok, socket} style
ericridgeway Feb 20, 2025
8e9e3d2
Add forgotten line break
ericridgeway Feb 20, 2025
eb00286
Remove 2nd attach_hook example and link directly to the first
ericridgeway Feb 20, 2025
0295a51
Update lib/phoenix_live_view.ex
Gazler Feb 20, 2025
d8f746d
Update guides/introduction/welcome.md
SteffenDE Feb 20, 2025
7b8ec2e
Update guides/introduction/welcome.md
SteffenDE Feb 20, 2025
6bfe7a0
Update guides/introduction/welcome.md
SteffenDE Feb 20, 2025
d0854c5
Update guides/introduction/welcome.md
SteffenDE Feb 20, 2025
2ec5dc0
Update guides/introduction/welcome.md
SteffenDE Feb 20, 2025
adb0bd0
Update guides/introduction/welcome.md
SteffenDE Feb 20, 2025
9e08247
Update guides/introduction/welcome.md
SteffenDE Feb 20, 2025
cb10fbe
Reverse locations of long-code-example & link-to-that-example
ericridgeway Feb 21, 2025
c59c5b2
Rename "Organizing code" section -> "Sharing event handling logic"
ericridgeway Feb 21, 2025
27f89da
Continue minimizing changes to welcome.md
ericridgeway Feb 21, 2025
200e77d
Apply suggestions from code review
josevalim Feb 21, 2025
89d1a06
Apply suggestions from code review
SteffenDE Feb 23, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 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 seperate 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 seperate 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,9 @@ 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:

### Summary
* use `Phoenix.Component` for code organization and reusing markup
* pair `Phoenix.Component` with [`attach_hook/4`](`Phoenix.LiveView.attach_hook/4#sharing-event-handling-logic`) to organize and reuse event handling
* 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 seperate 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
Loading