1
更新域動態我複製此代碼,所以任何人都可以嘗試一下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" ]
]
我最小下地兩(標題和蛞蝓),但也有其他人一樣:內容,摘錄。 ..
是否有反正我可以更新記錄而不創建所有字段的情況下,像只更新必要的字段,而不通過所有的字段?
是的,我這樣做,首先,我在尋找更有效的方式,而不是每個字段的功能更新,(我有一些車型誰不超過12個字段) – kayne
我喜歡這個答案Elm記錄是一種靜態類型。如果我想要有動態的東西,那麼我會使用'Dict'或其他東西。 – Tosh
謝謝你們,我認爲這是榆樹的方式,寫得太多了,我會堅持下去 – kayne