对话框中的“保存”按钮触发了导致页面刷新的重定向,因此我通过将对话框替换为带有字段的一些小部件,使用app.jsphx-hook
将聊天发送到服务器来解决此问题:pushEvent
index.html.leex
<input id="usernameinput" placeholder="Your name" phx-update="ignore"/>
<input id="chatinput" placeholder="Say something"/>
<button id="newchatbtn" phx-hook="ChatSend">Send</button>
应用程序.js:
Hooks.ChatSend = {
mounted() {
let viewHook = this
this.el.addEventListener("click", function() {
let uni = document.getElementById("usernameinput")
let ci = document.getElementById("chatinput")
viewHook.pushEvent("send-chat", {msg: ci.value, username: uni.value})
})
}
}
索引.ex:
@impl true
def handle_event("send-chat", %{"msg" => msg, "username" => username}, socket) do
{:ok, c} = Chats.create_chat(%{username: username, body: msg})
cs = socket.assigns.chats
cs = cs ++ [c]
socket = assign(socket, :chats, cs)
{:noreply, socket}
end
这是提交。