榆树 - 在Elm中动态更新字段

时间:2016-10-20 20:31:51

标签: elm

我复制了此代码,以便任何人都可以试用http://elm-lang.org/try

import Html exposing (..)
import Html.App as App
import Html.Attributes exposing (..)
import Html.Events exposing (..)


main =
  App.program
  { init = init
  , view = view
  , update = update
  , subscriptions = \_ -> Sub.none
  }


init =
  ( { posts = [], newPost = { title = "", slug = "" } }, Cmd.none )


type alias Post =
  { title : String
  , slug : String
  }


type alias Model =
  { posts : List Post
  , newPost : Post
  }


type Msg
  = NoOp
  | NewPostField Post String String


update msg model =
  case msg of

    NoOp ->
      ( model, Cmd.none )

    NewPostField currentPost field newValue ->
      case field of

        "title" ->
          ( { model | newPost = { slug = currentPost.slug, title = newValue } }, Cmd.none )

        "slug" ->
          ( { model | newPost = { slug = newValue, title = currentPost.title } }, Cmd.none )

       -- The problem is here, I have to repeat this process for every field

        _ ->
          ( model, Cmd.none )


view model =
  div []
    [ h1 [] [ text ("title : " ++ model.newPost.title ++ " | slug : " ++ model.newPost.slug) ]
    , input [ onInput (NewPostField model.newPost "title"), placeholder "Title" ] []
    , input [ onInput (NewPostField model.newPost "slug"), placeholder "Slug" ] []
    , button [] [ text "Save" ]
  ]

我将字段最小化为两个(标题和slug),但还有其他如:content,excerpt ...

无论如何我是否可以在不创建所有字段的情况下更新记录,例如只更新必要字段而不通过所有字段?

1 个答案:

答案 0 :(得分:4)

我会在您的代码中更改以下内容:

如果您针对每个操作都有特定的消息,则可以使用更清晰的updateview功能。编译器还将帮助您检查是否处理了所有情况,并且没有传递无意义的参数。

type Msg
  = NoOp
  | NewPostTitle Post String
  | NewPostSlug Post String

这不会为您节省太多打字,但您的update将如下所示。请注意,您不再具有嵌套模式匹配。另外,请注意updating records的语法,一次一个字段。

update msg model =
  case msg of
    NoOp ->
      ( model, Cmd.none )
    NewPostTitle currentPost value ->
      ( { model | newPost = { currentPost | title = value } }, Cmd.none )
    NewPostSlug currentPost value ->
      ( { model | newPost = { currentPost | slug = value } }, Cmd.none )

最后,在您的视图中,您不必传递字符串参数,这使代码更简洁。但真正重要的是现在它是类型安全的。

view model =
  div []
    [ h1 [] [ text ("title : " ++ model.newPost.title ++ " | slug : " ++ model.newPost.slug) ]
    , input [ onInput (NewPostTitle model.newPost), placeholder "Title" ] []
    , input [ onInput (NewPostSlug model.newPost), placeholder "Slug" ] []
    , button [] [ text "Save" ]
  ]