2016-10-20 121 views
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" ] 
    ] 

我最小下地兩(標題和蛞蝓),但也有其他人一樣:內容,摘錄。 ..

是否有反正我可以更新記錄而不創建所有字段的情況下,像只更新必要的字段,而不通過所有的字段?

回答

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" ] 
    ] 
+0

是的,我這樣做,首先,我在尋找更有效的方式,而不是每個字段的功能更新,(我有一些車型誰不超過12個字段) – kayne

+0

我喜歡這個答案Elm記錄是一種靜態類型。如果我想要有動態的東西,那麼我會使用'Dict'或其他東西。 – Tosh

+0

謝謝你們,我認爲這是榆樹的方式,寫得太多了,我會堅持下去 – kayne