我想使用动态字段名称来更新字段。在我的示例中,我有两个div
和contenteditable
属性。在blur
事件中,我需要更新模型(每个div更新其字段)。
module UpdateTest exposing (main)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (on)
import Json.Decode as Json
import Debug
type alias Model =
{ field1 : String
, field2 : String
}
type Msg = Update String String
main : Program () Model Msg
main =
Browser.element
{ init = init
, subscriptions = subscriptions
, view = view
, update = update
}
init : () -> ( Model, Cmd Msg )
init () =
( { field1 = "value 1", field2 = "value2" }, Cmd.none )
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
view : Model -> Html Msg
view model =
div []
[ div [ contenteditable True, attribute "data-id" "field1", onBlur (Update "field1") ] [ text model.field1 ]
, div [ contenteditable True, attribute "data-id" "field2", onBlur (Update "field2") ] [ text model.field2 ]
, div [ id "fiedl11" ] [ text model.field1 ]
, div [ id "fiedl12" ] [ text model.field2 ]
]
onBlur : (String -> msg) -> Attribute msg
onBlur tagger =
on "blur" (Json.map tagger targetTextContent)
targetTextContent : Json.Decoder String
targetTextContent =
Json.at ["target", "textContent"] Json.string
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Update id text ->
({model | id = Debug.log id text }, Cmd.none) -- here the issue
你认为有更好的东西吗?
Elm是一种静态类型的语言,因此无法使用字符串值来引用记录的字段,因为这会导致在运行时发生类型错误。
Elm还缺少任何类型的运行时自省/反射,因此您无法在运行时获取类型信息,该信息会使您自动将字符串与记录的字段名称进行匹配。
您将需要执行以下操作:
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Update id text -> case id of
"field1" -> ({model | field1 = text }, Cmd.none)
"field2" -> ({model | field2 = text }, Cmd.none)