程序

当你的应用程序不需要任何外部数据进行初始化时,program 是一个很好的选择。

它能够处理订阅和命令,从而为处理 I / O 提供更多机会,例如 HTTP 通信或与 JavaScript 互操作。

初始状态需要与模型一起返回启动命令。

program 的初始化将需要提供 subscriptions,以及 modelviewupdate

查看类型定义:

program :
    { init : ( model, Cmd msg )
    , update : msg -> model -> ( model, Cmd msg )
    , subscriptions : model -> Sub msg
    , view : model -> Html msg
    }
    -> Program Never

最简单的说明方法是,如何使用 Subscriptions 来设置与 JavaScript 的简单端口通信。

了解如何在 Initialize 和 build / Embedding into HTML 中构建示例

port module Main exposing (..)

import Html exposing (Html, text)
import Html exposing (program)

main : Program Never
main =
    program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }

port input : (Int -> msg) -> Sub msg

-- MODEL

type alias Model =
    Int

init : ( Model, Cmd msg )
init =
    ( 0, Cmd.none )

-- UPDATE

type Msg = Incoming Int

update : Msg -> Model -> ( Model, Cmd msg )
update msg model =
    case msg of
        Incoming x ->
          ( x, Cmd.none )

-- SUBSCRIPTIONS

subscriptions : Model -> Sub Msg
subscriptions model =
    input Incoming

-- VIEW

view : Model -> Html msg
view model =
    text (toString model)
<!DOCTYPE html>
<html>
    <head>
        <script src='elm.js'></script>
</head>
    <body>
    <div id='app'></div>
    <script>var app = Elm.Main.embed(document.getElementById('app'));</script>
    <button onclick='app.ports.input.send(1);'>send</button>
</body>
</html>