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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
| # 初期接続
def mount(_params, session, socket) do
# セッションの確認
IO.inspect(session)
# 各初期値を取得( atom で入れても session 上では文字列にされるので注意
light_bulb_status = Map.get(session, "light_bulb_status", "off")
on_button_status = Map.get(session, "on_button_status", "")
off_button_status = Map.get(session, "off_button_status", "disabled")
# 初期値の確認
IO.inspect(light_bulb_status)
IO.inspect(on_button_status)
IO.inspect(off_button_status)
socket =
socket
|> assign(:light_bulb_status, light_bulb_status)
|> assign(:on_button_status, on_button_status)
|> assign(:off_button_status, off_button_status)
# セッションの共有
|> PhoenixLiveSession.maybe_subscribe(session)
{:ok, socket}
end
# 画面
def render(assigns) do
~L"""
<h1>The light is <%= @light_bulb_status %>.</h1>
<button phx-click="on" <%= @on_button_status %>>On</button>
<button phx-click="off" <%= @off_button_status %>>Off</button>
"""
end
# Onボタンの処理
def handle_event("on", _value, socket) do
socket =
socket
|> assign(:light_bulb_status, "on")
|> assign(:on_button_status, "disabled")
|> assign(:off_button_status, "")
# セッションに保存
|> PhoenixLiveSession.put_session(:light_bulb_status, "on")
|> PhoenixLiveSession.put_session(:on_button_status, "disabled")
|> PhoenixLiveSession.put_session(:off_button_status, "")
{:noreply, socket}
end
# Offボタンの処理
def handle_event("off", _value, socket) do
socket =
socket
|> assign(:light_bulb_status, "off")
|> assign(:on_button_status, "")
|> assign(:off_button_status, "disabled")
# セッションに保存
|> PhoenixLiveSession.put_session(:light_bulb_status, "off")
|> PhoenixLiveSession.put_session(:on_button_status, "")
|> PhoenixLiveSession.put_session(:off_button_status, "disabled")
{:noreply, socket}
end
end
|