Skip to content

Commit

Permalink
update counter live to subscribe and boradcast msgs #1
Browse files Browse the repository at this point in the history
  • Loading branch information
RobStallion committed Jun 6, 2019
1 parent 6a569ea commit 5475eb4
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions lib/live_view_counter_web/live/counter_live.ex
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
defmodule LiveViewCounterWeb.CounterLive do
use Phoenix.LiveView

@topic "live"

def render(assigns) do
~L"""
<div>
Expand All @@ -12,14 +14,23 @@ defmodule LiveViewCounterWeb.CounterLive do
end

def mount(_session, socket) do
LiveViewCounterWeb.Endpoint.subscribe(@topic)
{:ok, assign(socket, :val, 0)}
end

def handle_event("inc", _, socket) do
{:noreply, update(socket, :val, &(&1 + 1))}
def handle_event("inc", _value, socket) do
new_state = update(socket, :val, &(&1 + 1))
LiveViewCounterWeb.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))
LiveViewCounterWeb.Endpoint.broadcast_from(self(), @topic, "dec", new_state.assigns)
{:noreply, update(socket, :val, &(&1 - 1))}
end

def handle_info(msg, socket) do
{:noreply, assign(socket, msg.payload)}
end
end

0 comments on commit 5475eb4

Please sign in to comment.