Elm Language The Elm Architecture Program with Flags


Example

programWithFlags has only one difference from program.

It can accept the data upon initialization from JavaScript:

var root = document.body;
var user = { id: 1, name: "Bob" };
var app = Elm.Main.embed( root, user );

The data, passed from JavaScript is called Flags.

In this example we are passing a JavaScript Object to Elm with user information, it is a good practice to specify a Type Alias for flags.

type alias Flags =
    { id: Int
    , name: String
    }

Flags are passed to the init function, producing the initial state:

init : Flags -> ( Model, Cmd Msg )
init flags =
    let
        { id, name } =
            flags
    in
        ( Model id name, Cmd.none )

You might notice the difference from it's type signature:

programWithFlags :
    { init : flags -> ( model, Cmd msg )          -- init now accepts flags
    , update : msg -> model -> ( model, Cmd msg )
    , subscriptions : model -> Sub msg
    , view : model -> Html msg
    }
    -> Program flags

The initialization code looks almost the same, since it's only init function that is different.

main =
    programWithFlags
        { init = init
        , update = update
        , view = view
        , subscriptions = subscriptions
        }