module Main exposing (..)
import Html exposing (beginnerProgram, div, button, text)
import Html.Events exposing (onClick)
main =
beginnerProgram { model = 0, view = view, update = update }
type Msg
= Transform (Int -> Int)
view model =
div []
[ button [ onClick (Transform ((+) -1)) ] [ text "-" ]
, div [] [ text (toString model) ]
, button [ onClick (Transform ((+) 1)) ] [ text "+" ]
]
update msg model =
case msg of
Transform xform ->
xform model
A part of me likes this since it can help simplify some code, like in this example where the "update" is reduced to a single case. You can even simplify it to a trivial line if you define Msg like this:
-----------------------
view model =
div []
[ button [ onClick <| (+) -1 ] [ text "-" ]
, div [] [ text (toString model) ]
, button [ onClick <| (+) 1 ] [ text "+" ]
]
type alias Msg = Int -> Int
update msg model = msg model
-----------------------
On the other hand defining the state logic from the view seems like an antipattern since now the view now has 2 responsabilities (structure and logic) and update practically has none. I'd be pragmatic and use it when it makes sense, but in general I see the disadvantage that you can pattern match against a function argument, e.g. you cant know if "(+) -1" or "(+) 1" was sent.
--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss+unsubscribe@googlegroups.com.
type Msg
= Add Int
view model =
div []
[ button [ onClick (Add -1) ] [ text "-" ]
, div [] [ text (toString model) ]
, button [ onClick (Add 1) ] [ text "+" ]
]
update msg model =
case msg of
Add delta ->
model + delta
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss...@googlegroups.com.
Model
or Msg
types. It may cost a little bit of extra code to model everything as data, but the architecture and debugging benefits are worth it.