简体   繁体   English

如何在 handle_event 函数中使用 phoenix 框架中的变量?

[英]How to use variable in phoenix framework in a handle_event function?

I would like to have two input fields in two different forms (see below).我想有两种不同形式的两个输入字段(见下文)。 The first one submits the user's name and saves it in variable client_name.第一个提交用户名并将其保存在变量 client_name 中。 This seems to work fine.这似乎工作正常。

When the second one is submitted, I would like to grab hold of the client_name variable and use it in the string I create.当第二个提交时,我想抓住 client_name 变量并在我创建的字符串中使用它。 But I don't know how.但我不知道怎么办。

defmodule ChatWeb.ChatLive do 
use ChatWeb, :live_view

@topic "message_received"

    def mount(params, session, socket) do
        ChatWeb.Endpoint.subscribe(@topic)
        {:ok, assign(socket, :text_value, "") |>assign(:client_name, "")}
    end
    
    def render(assigns) do
    ~H"""
        <h1>Chat</h1>
        <form phx-submit="submit_name">
            <label>Your name: <%= @client_name %><input id="client" type="text" name="client" /></label>
            <input type="submit" />
        </form>
        <form phx-submit="submit">
            <label>Your Text:<input id="msg" type="text" name="input_value" /></label>
            <input type="submit" />
        </form>
        <div id="chat">
            Chat history: <%= @text_value %>
        </div>
        
    """
    end
    
    def handle_event("submit_name", %{"client" => client}, socket) do
        {:noreply, assign(socket, :client_name, client)}
    end
    
    def handle_event("submit", %{"input_value" => msg}, socket) do
        ChatWeb.Endpoint.broadcast_from(self(), @topic, "message_received_received", "| Message by #{client_name}: '" <> msg <> "' ")
        {:noreply, assign(socket, :text_value, "| Message by #{client_name}: '" <> msg <> "' " <> socket.assigns.text_value)}
    end
    
    def handle_info(%{topic: @topic, payload: new_message}, socket ) do
        {:noreply, assign(socket, :text_value, new_message <> socket.assigns.text_value)}
    end
    

end结尾

The Problem is with the #{client_name} What would be the correct notation?问题出在#{client_name} 什么是正确的表示法?

My error says: undefined function client_name/0我的错误是:undefined function client_name/0

Your call to client_name should be changed to socket.assigns.client_name as this is where you put the value in the handle_event("submit_name", ...) .您对client_name的调用应更改为socket.assigns.client_name因为这是您将值放入handle_event("submit_name", ...)的位置。

Alternatively you can bind the client_name assign in the function clause:或者,您可以在函数子句中绑定client_name赋值:

def handle_event("submit", %{"input_value" => msg}, %{assigns: %{client_name: client_name}} = socket) do

In this case you don't need to fix client_name in the function body.在这种情况下,您不需要在函数体中修复client_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM