這個圖就是Elm 的架構,也是後來redux所延用的架構,懂這張圖elm就學會了(咦?)
簡單來說,一個Elm 的app 是由這三個組成的,一個是View(對,你沒看錯,Html用Elm
來寫,很簡單,後話我們再說。),一個就是Update,譬如你按了一個按鈕,文字就變成紅色。還有一個是Model,通常是用record來表示,像上一篇的Person Record
, 你傳給View,變成了一個list-like,按了按鈕,於是update 新的顏色。
不只是改變 View
(改變html),也可以有 Cmd
(這個通常可以傳出http request等),或是你有 Sub
(ex.
for web socket)。不過我們先可以理解就是為了改變 View
先來講講Elm 的 View 好了。非常簡單,和本來寫html 的差異不大,
code在這裡,因為it邦好像不能看iframe, 如果想要看code請點:
ellie
module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
model =
{ result =
{ id = 1
, name = "TheSeamau5/elm-checkerboardgrid-tutorial"
, stars = 66
}
}
main =
let
elmHubHeader =
header []
[ h1 [] [ text "ElmHub" ]
, span [ class "tagline" ] [ text "Like GitHub, but for Elm things." ]
]
in
div [ class "content" ]
[ elmHubHeader
, ul [ class "results" ]
[ li []
[ span [ class "star-count" ] [ text (toString model.result.stars) ]
, a [ href ("https://github.com/" ++ model.result.name) ] [ text model.result.name ]
]
]
]
-- source from https://github.com/rtfeldman/elm-workshop/tree/solutions/part2
以 h1
為例,它是 elm 裡的一個function, 他有兩個parameter:
text "ElmHub"
這個Ellie的例子可以再看看,也有html 和render 出來的網頁來比較,看懂就會寫基本的Elm 裡的 view 了!
main : Program Config Model Msg
main =
Html.programWithFlags
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
這是我在builtwithelm上任意找到的一個專案裡,Main.elm
的一小部分,。就可以看到這個TEA的架構了。
如果我們去看看官方文版寫什麼:
program
: { init : (model, Cmd msg), update : msg -> model -> (model, Cmd msg), subscriptions : model -> Sub msg, view : model -> Html msg }
-> Program Never model msg
Create a Program that describes how your whole app works.
Read about The Elm Architecture to learn how to use this. Just do it. Commands and subscriptions make way more sense when you work up to them gradually and see them in context with examples.
Html
套件內有個 program
, beginnerProgram
, ProgramWithFlags
等都可以幫你把這個Platform建起來,就會有完整的view, update, model等等的the elm architecture。Program
是一個type定義在 Platform
套件裡的:type Program flags model msg
A Program describes how to manage your Elm app.
如果你知道haskell的話,
main :: IO ()
main = do
-- something here
Program Never
可以想成是 IO ()
的Elm 版本。
如果你不知道haskell 也沒有關係。這樣子就是建立好一個完整的Elm app。可以開始運作啦。