javascript - 如何从 javascript 与 liveview 正确通信
问题描述
我正在尝试在触发 Javascript 事件后使用 Javascript 更新 Liveview。Liveview 必须显示<div>
带有从 Javascript 发送的一些值的元素。
我的问题是:我应该如何将这些值从 Javascript 传递到 Liveview?
我可能还需要 Liveview 在 Javascript 中发送的值。再说一遍:我应该如何将这些值从 Liveview 传递给 Javascript?
在 Javascript 中创建了一个 Livesocket 以供 liveview 工作,但我看不到从那里获取或设置分配值的方法。从/到 Liveview 传递值的唯一方法似乎是在某些时候通过 DOM。例如:
<div id="lv-data" phx-hook="JavascriptHook"></div>
let hooks = {};
hooks.JavascriptHook = {
mounted(){
this.el.addEventListener("jsEvent", (e) =>
this.pushEvent("jsEventToPhx", e.data, (reply, ref) =>
console.log("not sure what to do here")));
this.handleEvent("phxEventToJS", (payload) => console.log("data received: " + payload));
}
}
这感觉很奇怪,必须使用带有假人的 DOM 来<div>
进行纯粹的数据交换......
解决方案
您的LiveView
模块是否已实施以处理jsEventToPhx
您从前端发送的事件?您必须有一个父级LiveView
或LiveViewComponent
实现handle_event/3
此消息的回调。看:
https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#c:handle_event/3
例如(在您的 LiveView 模块中):
def handle_event("jsEventToPhx", params, socket) do
# Here the `params` variable is what you are sending form the
# client-side, so it will be `%{foo: "bar"}` if you
# follow the next example.
{:reply, %{hello: "world"}, socket}
end
然后在你的 Hook 中,你只需要使用this.pushEvent
:
let hooks = {};
hooks.JavascriptHook = {
mounted(){
this.pushEvent("jsEventToPhx", {foo: "bar"}, (reply, ref) =>
// this will print `{hello: "world"}`
console.log(reply);
}
}
}
当您想要将数据发送到 LiveView 并选择立即接收响应时,这是一种方法。
如果你想向LiveView
客户端发送一些东西,那么这个过程会略有不同。push_event
从任何回调返回套接字时使用的 LiveView handle_event
,例如:
{:noreply, push_event(socket, "phxEventToJS", %{abc: "xyz"})}
在你的 Hook 中,你订阅了事件:
mounted(){
this.pushEvent("jsEventToPhx", {foo: "bar"}, (reply, ref) =>
// this will print `{hello: "world"}`
console.log(reply);
}
this.handleEvent("phxEventToJS", (payload) => {
// this will print `{abc: "xyz"}`
console.log(payload);
}
}
在此处检查客户端-服务器通信部分可能很有用。
推荐阅读
- firebase - Firebase Image Resizer url 仅在两次提交相同的图像或创建令牌后才有效
- python - 在同一图形上绘制直方图和折线图
- java - 使用 JsonNode 错误地解析日期字段
- javascript - 如何居中并减少这些链接之间的空间?
- php - foreach 循环中的数据库查询使我的应用程序变慢
- git - 使用 .gitignore 允许异常
- c# - 实体框架无法加载子类(急切加载)
- c# - c# 中的字符串插值我在做什么错?
- python - Pandas:如何从其他列的过滤值中获取该列的平均值?
- c# - 将数据导出到 CSV 时如何获取 DataTable 列名称?