将数据从Phoenix传递到Javascript的最佳实践 [英] Best practice to pass data from Phoenix to Javascript

查看:56
本文介绍了将数据从Phoenix传递到Javascript的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了三种实现方法.

I see 3 ways of doing this.

  1. *.html.eex<script>中使用<%= %>
  2. 使用渠道将数据传递给Javascript
  3. 构建一个json api
  1. Using <%= %> inside <script> in *.html.eex
  2. Use channels to pass data to Javascript
  3. Build a json api

#1似乎是最简单的方法,但我还没有找到或想到实现此目的的好方法.

#1 seems the easiest but I couldn't find or think of a good way to do it yet.

注意:实时更新不是我的要求.

Note: real-time update is not my requirement.

推荐答案

我永远不会为此使用<script></script>,在我的项目中,我使用以下模式:

I would never use a <script></script> for that, in my projects I have this pattern:

<!-- Layout -->
<div id="config"
  data-environment="..."
></div>

我总是在主布局中提供当前环境,我有一个config.js文件,其中包含适用于正确环境的正确数据.

I always provide the current environment in the master layout, I have a config.jsfile with the right data for the right environment.

当我需要将一些数据传递给javascript时,我会在视图中执行以下操作:

When I need to pass some data to my javascript I do something like that in my view:

<div id="app"
  data-users="..."
  data-zombies="..."
  ...
></div>

如果您通过一些助手(elixir方面)来抽象您可以做到的话,

If you abstract that with some helpers (elixir side) you can do:

<%= App.Helpers.make_html(:app, [users: @users, zombies: @zombies]) %>

在javascript端,当我加载页面时,我只是提取data-属性并将其设置在当前控制器的变量options中:

In the javascript side, when I load the page I just extract the data-attributes and set them in a variable options for the current controller:

class ZombieController extends Controller

  setup: ->

    console.log(@options) # I have all the data there.

    # I can do 
    zombies = @options.zombies

嗯,这只是一个例子,您应该针对当前项目进行调整.关键是抽象.

Well, it's just an example and you should adapt that for your current project. The key is to abstract.

希望它会有所帮助:)

Hope it helps :)

这篇关于将数据从Phoenix传递到Javascript的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆