duanba4942 2017-02-22 06:36
浏览 38
已采纳

将Elm与现有的Web应用程序服务集成的正确方法

i have a backend service that I wrote in Golang, something like this:

func PageA_RequestHandler(ctx *W.Context) {
  // init things
  if is_ajax {
    // handle the API request, render the JSON
    return
  }
  // query the initial rows
  values := M.SX{
    `rows`: model1.GetRows(10),
    `columns`: model1.GetColumns(),
  }
  // render the html
  ctx.Render(`page_a_template`,values)
}

then the template file page_a_template.html (that loaded and cached at the first time it rendered), is a html file, with content something like this:

<div id="grid"></div>
<script>
  var rows = {/* rows */};
  var cols = [/* columns */]
  new GridBuilder('grid',cols,rows);
</script>

Where's:

{/* rows */} and [/* columns */] are my javascript-friendly template syntax, there are some other syntax like: /*! bar */ or #{yay}

new GridBuilder is my custom javascript component that creates something like datatables.net or editablegrid.net

The question is, if I use Elm, what's the correct way to inject the {/* rows */} into the compiled html?

  • 写回答

1条回答 默认 最新

  • dongyi1159 2017-02-22 19:04
    关注

    Use Html.programWithFlags (supposing your main module is named App):

    <div id="grid"></div>
    <script>
      var rows = {/* rows */};
      var cols = [/* columns */];
      var node = document.getElementById('grid');
      Elm.App.embed(node, { rows: rows, cols: cols });
    </script>
    

    This is the way you can initialize your Elm app with available data just like you are initializing GridBuilder.

    To be able to read those values, you should create a Flags type alias and your init function will receive it.

    type alias Flags =
        { rows : [ ... ]
        , cols : [ ... ]
        }
    
    init : Flags -> ( Model, Cmd Msg )
    init flags =
        ...
    

    Your main function will look like this:

    main =
        Html.programWithFlags
            { init = init, ... }
    

    I highly recommend that you read the JavaScript Interop section of the Elm Guide. It explains the programWithFlags and other approaches to receive/send data from/to JavaScript.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题