如何在动态生成的视图中更新模型?

时间:2018-10-08 13:27:01

标签: elm

import Browser
import Html exposing (Html, button, div, text)
import Html.Attributes exposing (disabled)
import Html.Events exposing (onClick)


main =
    Browser.sandbox
        { init =
            { count = 0
            , node = text ""
            , inactive = False
            }
        , update = update
        , view = view
        }


type Msg
    = Increment
    | AddNode


update msg model =
    case msg of
        Increment ->
            Debug.log "count"
                { model
                    | count = model.count + 1
                }

        AddNode ->
            let
                viewDynamic =
                    div []
                        [ text (String.fromInt model.count) ]
            in
            { model
                | node =
                    div []
                        [ button [ onClick Increment ] [ text "+" ]
                        , viewDynamic
                        ]
                , inactive = True
            }


view model =
    let
        viewStatic =
            button
                [ disabled model.inactive
                , onClick AddNode
                ]
                [ text "new" ]
    in
    div []
        [ viewStatic
        , model.node
        ]

以上,初始静态视图可以对model.inactive的更新做出反应,但是随后的动态视图无法更新model.count。如何理想地实现它?

1 个答案:

答案 0 :(得分:0)

理想地解决了@glennsl的提示。

import Browser
import Html exposing (Html, button, div, text)
import Html.Attributes exposing (disabled)
import Html.Events exposing (onClick)


main =
    Browser.sandbox
        { init =
            { count = 0
            , added = False
            , inactive = False
            }
        , update = update
        , view = view
        }


type Msg
    = Increment
    | AddNode


update msg model =
    case msg of
        Increment ->
            { model | count = model.count + 1 }

        AddNode ->
            { model | inactive = True, added = True }


view model =
    let
        viewStatic =
            button
                [ disabled model.inactive
                , onClick AddNode
                ]
                [ text "new" ]

        viewDynamic =
            div []
                [ text (String.fromInt model.count) ]
    in
    div []
        [ viewStatic
        , if model.added then
            div []
                [ button [ onClick Increment ] [ text "+" ]
                , viewDynamic
                ]

          else
            text ""
        ]