gpt4 book ai didi

javascript - 在 Phoenix 框架应用程序的某些页面上包含 Javascript

转载 作者:行者123 更新时间:2023-12-03 01:28:51 24 4
gpt4 key购买 nike

我有一些 Javascript,我只想将其包含在 Phoenix 应用程序的某些页面上。

现在,我已经在 myapp/web/templates/post/form.html.eex 的脚本标记内获取了 Javascript。

我知道我可以将 JavaScript 移动到 web/static/js/app.js ...但我不想在每个页面上都包含 JavaScript(仅在 2 个页面上需要)特定页面)。

在我的应用程序的某些页面上加载这部分 Javascript 的最佳方法是什么,而不需要重复代码和违反 DRY 原则?

最佳答案

1.

form.html.eex 中的所有 javascript 放入其自己的文件中(可能类似于 js/posts.js)。

在底部添加此内容:

export var Post = { run: function() {
// put initializer stuff here
// for example:
// $(document).on('click', '.remove-post', my_remove_post_function)
}}

2.

在您的 app.html 中,<script src="#{static_path(@conn, "/js/app.js")}"></script> 下添加此:

<%= render_existing @view_module, "scripts.html", assigns %>

3.

然后,在您的 View (可能是views/post_view.ex)中,添加如下方法:

def render("scripts.html", _assigns) do
~s{<script>require("web/static/js/posts").Post.run()</script>}
|> raw
end

结论

现在,JavaScript 文件 post.js 只会在使用帖 subview 时加载。

关于javascript - 在 Phoenix 框架应用程序的某些页面上包含 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36629942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com