mirror of
https://github.com/woutdp/live_svelte
synced 2026-05-24 09:28:21 +00:00
Refactor BreakingNewsLive
This commit is contained in:
parent
185b1f84c0
commit
a1d5ed9cbf
1 changed files with 13 additions and 12 deletions
|
|
@ -1,10 +1,12 @@
|
|||
defmodule ExamplesWeb.BreakingNewsLive do
|
||||
defmodule ExampleWeb.BreakingNewsLive do
|
||||
use ExampleWeb, :live_view
|
||||
|
||||
@initial_news [
|
||||
%{body: "World peace has been achieved!", id: 1},
|
||||
%{body: "Some other crazy stuff happened", id: 2},
|
||||
%{body: "Car crash in city center", id: 3}
|
||||
%{id: 1, body: "Giant Pink Elephant Sighted Downtown"},
|
||||
%{id: 2, body: "Local Cat Becomes Mayor of Small Town"},
|
||||
%{id: 3, body: "Scientists Discover New Flavor of Ice Cream"},
|
||||
%{id: 4, body: "World's Largest Pizza Baked in Local Pizzeria, Still Not Big Enough for Customers"},
|
||||
%{id: 5, body: "Clown Epidemic Sweeps Through Town, Everyone Laughs Until They Realize the Clowns Aren't Joking"},
|
||||
]
|
||||
|
||||
def render(assigns) do
|
||||
|
|
@ -17,15 +19,14 @@ defmodule ExamplesWeb.BreakingNewsLive do
|
|||
{:ok, assign(socket, :news, @initial_news)}
|
||||
end
|
||||
|
||||
def handle_event("remove_news_item", %{"id" => id} = params, socket) do
|
||||
socket = assign(socket, :news, Enum.reject(socket.assigns.news, fn item -> item.id == id end))
|
||||
{:noreply, socket}
|
||||
def handle_event("remove_news_item", %{"id" => id}, socket) do
|
||||
updated_news = Enum.reject(socket.assigns.news, fn item -> item.id == id end)
|
||||
{:noreply, assign(socket, :news, updated_news)}
|
||||
end
|
||||
|
||||
def handle_event("add_news_item", %{"body" => item} = params, socket) do
|
||||
new_item = %{body: item, id: get_id()}
|
||||
{:noreply, assign(socket, :news, socket.assigns.news ++ [new_item])}
|
||||
def handle_event("add_news_item", %{"body" => body}, socket) do
|
||||
new_item = %{id: System.unique_integer([:positive]), body: body}
|
||||
updated_news = socket.assigns.news ++ [new_item]
|
||||
{:noreply, assign(socket, :news, updated_news)}
|
||||
end
|
||||
|
||||
def get_id(), do: System.unique_integer([:positive])
|
||||
end
|
||||
|
|
|
|||
Loading…
Reference in a new issue