如何在Phoenix的控制器中触发频道广播
How to trigger channel broadcast in the controller in Phoenix
我正在尝试弄清楚如何从控制器触发频道广播。
例子
def create(conn, %{"message" => message_params}) do
with {:ok, %Message{} = message} <- Chat.create_message(message_params) do
conn
# TRIGGER CHANNEL BROADCAST "SHOUT" HERE
|> put_status(:created)
|> put_resp_header("location", message_path(conn, :show, message))
|> render("show.json", message: message)
end end
water_cooler频道
defmodule NotificationWeb.WaterCoolerChannel do
use NotificationWeb, :channel
def join("water_cooler:lobby", _payload, socket) do
{:ok, socket}
end
def handle_in("shout", payload, socket) do
broadcast socket, "shout", payload
{:noreply, socket}
end
end
我试过使用 NotificationWeb.broadcast(topic, event, msg)
但不知道该放什么
主题 = "water_cooler" ?
事件 = ?
消息=?
可以使用 NotificationWeb.Endpoint
的 broadcast 功能广播消息。
topic
这里是你要直播的房间(比如water_cooler:lobby
)
event
是事件的名称,你希望在客户端收到
msg
是事件中的附加信息
考虑到您在前端部分有这样的东西:
channel.on("new_msg", payload => {
// process new message
})
则 event
等于 new_msg
,msg
是数据,此事件中的 payload
变量将包含
我正在尝试弄清楚如何从控制器触发频道广播。
例子
def create(conn, %{"message" => message_params}) do
with {:ok, %Message{} = message} <- Chat.create_message(message_params) do
conn
# TRIGGER CHANNEL BROADCAST "SHOUT" HERE
|> put_status(:created)
|> put_resp_header("location", message_path(conn, :show, message))
|> render("show.json", message: message)
end end
water_cooler频道
defmodule NotificationWeb.WaterCoolerChannel do
use NotificationWeb, :channel
def join("water_cooler:lobby", _payload, socket) do
{:ok, socket}
end
def handle_in("shout", payload, socket) do
broadcast socket, "shout", payload
{:noreply, socket}
end
end
我试过使用 NotificationWeb.broadcast(topic, event, msg)
但不知道该放什么
主题 = "water_cooler" ?
事件 = ?
消息=?
可以使用 NotificationWeb.Endpoint
的 broadcast 功能广播消息。
topic
这里是你要直播的房间(比如water_cooler:lobby
)event
是事件的名称,你希望在客户端收到msg
是事件中的附加信息
考虑到您在前端部分有这样的东西:
channel.on("new_msg", payload => {
// process new message
})
则 event
等于 new_msg
,msg
是数据,此事件中的 payload
变量将包含