简体   繁体   English

Elixir / Phoenix:对频道的看法?

[英]Elixir / Phoenix: Views for channels?

I'm creating a chat app and I have a bunch of channel messages. 我正在创建一个聊天应用程序,我有一堆频道消息。 Here's one of them: 这是其中之一:

def handle_in("read", %{ "chat_id" => chat_id }, socket) do
  user_id = socket.assigns[:id]

  ts = DateTime.utc_now
  case ChatManager.mark_as_read({user_id, chat_id, ts}) do
    {:ok, chat_user} ->
      last_read_at_unix = chat_user.last_read_at |> TimeConverter.ecto_to_unix
      {:reply, {:ok, %{ chat_id: chat_id, last_read_at: last_read_at_unix }}, socket}
    {:error, changeset} ->
      {:reply, {:error, %{errors: changeset.errors}}, socket}
  end
end

Can I use phoenix Views to separate my presentation / response logic? 我可以使用凤凰视图来分离我的演示/响应逻辑吗? This way I can just quickly go to a view file and see what is returned by each message. 这样我就可以快速转到视图文件,查看每条消息返回的内容。

Phoenix Views are just normal modules with functions in them. Phoenix Views只是具有功能的普通模块。

You can either call those functions directly: 您可以直接调用这些函数:

MyApp.Web.ChatView.render("message.json", %{message: my_message})

Or use a Phoenix.View function which would call the render/2 function of your view: 或者使用Phoenix.View函数调用视图的render/2函数:

Phoenix.View.render_one(MyApp.Web.ChatView, "message.json", message: my_message)

The Phoenix.View functions have a few advantages if your arguments are more dynamic (for example if you pass nil as the message). 如果您的参数更具动态性,那么Phoenix.View函数有一些优点(例如,如果您将nil作为消息传递)。

Consult the Phoenix.View documentation for details on those convenience functions. 有关这些便利功能的详细信息,请参阅Phoenix.View文档

When building a large application, it makes sense to have .json templates for all your models because you'll need to pass json around in API responses, as channel messages or serialized messages in a message queue. 构建大型应用程序时,为所有模型设置.json模板是有意义的,因为您需要在API响应中传递json,作为消息队列中的通道消息或序列化消息。 The views you've already written are reusable for all of those cases. 您已编写的视图可以在所有这些情况下重复使用。

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

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