-
Notifications
You must be signed in to change notification settings - Fork 38
/
counter.ex
36 lines (30 loc) · 1.05 KB
/
counter.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
defmodule CounterWeb.Counter do
use CounterWeb, :live_view
@topic "live"
def mount(_session, _params, socket) do
CounterWeb.Endpoint.subscribe(@topic) # subscribe to the channel
{:ok, assign(socket, :val, 0)}
end
def handle_event("inc", _value, socket) do
new_state = update(socket, :val, &(&1 + 1))
CounterWeb.Endpoint.broadcast_from(self(), @topic, "inc", new_state.assigns)
{:noreply, new_state}
end
def handle_event("dec", _, socket) do
new_state = update(socket, :val, &(&1 - 1))
CounterWeb.Endpoint.broadcast_from(self(), @topic, "dec", new_state.assigns)
{:noreply, new_state}
end
def handle_info(msg, socket) do
{:noreply, assign(socket, val: msg.payload.val)}
end
def render(assigns) do
~H"""
<div class="text-center">
<h1 class="text-4xl font-bold text-center"> Counter: <%= @val %> </h1>
<.button phx-click="dec" class="w-20 bg-red-500 hover:bg-red-600">-</.button>
<.button phx-click="inc" class="w-20 bg-green-500 hover:bg-green-600">+</.button>
</div>
"""
end
end