Program > JavaScript > AltJS > Elm > Elmガイド > Elmアーキテクチャー > ボタン
#code(haskell){{
import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
main =
Browser.sandbox { init = init, update = update, view = view }
type alias Model = Int
init : Model
init =
0
type Msg = Increment | Decrement
update : Msg -> Model -> Model
update msg model =
case msg of Increment -> model + 1
Decrement -> model - 1
view : Model -> Html Msg
view model =
div [] [ button [ onClick Decrement ] [ text "-" ] , div [] [ text (String.fromInt model) ] , button [ onClick Increment ] [ text "+" ] ]
}}
パッと見、雰囲気だけは伝わりますが、個々の部分を見ていくと、よく分からないコードですね。
UPDATEやVIEWの部分を見ると、関数の宣言方法が何となく分かります。
練習問題: The Elm Architectureが優れていることの一つに、プロダクトに変更が必要な場合はとても簡単に拡張できることが挙げられます。あなたのプロダクトマネージャが"reset"機能を思い付いたとしましょう。新しいボタンはカウンタを0にリセットします。
この機能を追加するにはMsg型の実装部分にもどってもう一つの可能性のResetを追加しましょう。メッセージを受け取ったときに何をすべきかをupdate関数に記述して下さい。最後はviewにボタンを追加して下さい。
それでは、"reset"機能を実装してみましょう!
適当に勘でやったらうまくいった!
#code(haskell){{
type Msg
= Increment | Decrement | Reset
update : Msg -> Model -> Model
update msg model =
case msg of Increment -> model + 1
Decrement -> model - 1 Reset -> model - model
view : Model -> Html Msg
view model =
div [] [ button [ onClick Decrement ] [ text "-" ] , div [] [ text (String.fromInt model) ] , button [ onClick Increment ] [ text "+" ] , div [] [] , button [ onClick Reset ] [ text "Reset" ] ]
}}
-- UNEXPECTED EQUALS ------------------------------------------- Jump To Problem I was not expecting to see this equals sign: 55| model = 0 ^ Maybe you want == instead? To check if two values are equal? Note: I may be getting confused by your indentation. I think I am still parsing the `update` definition. Is this supposed to be part of a definition after that? If so, the problem may be a bit before the equals sign. I need all definitions to be indented exactly the same amount, so the problem may be that this new definition has too many spaces in front of it.
自分なりの工夫は、model - modelという計算式を入れたことかな。
本当はどうやるのがスマートなのだろう?