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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。