Checkbox example

574 views
Skip to first unread message

Mark Hamburg

unread,
Nov 16, 2016, 11:56:02 AM11/16/16
to elm-d...@googlegroups.com
The checkbox example on the Elm site initializes the model to have all the checkboxes set, but does not reflect this state when it runs since it never feeds the model values through to the view.

I notice this in a lot of Elm examples. For example, the sign up form example doesn't populate the model values into the text fields. Is this just a case on relying on the model having been initialized in the same way the fields default and then just expecting to track changes? That seems like a bad pattern in more common practice.

Mark

Message has been deleted

Desmond D'Souza

unread,
Nov 16, 2016, 3:55:12 PM11/16/16
to Elm Discuss
Try feeding the model property through to view :

view : Model -> Html Msg
view model =
  fieldset []
    [ checkbox model.notifications ToggleNotifications "Email Notifications"
    , checkbox model.autoplay ToggleAutoplay "Video Autoplay"
    , checkbox model.location ToggleLocation "Use Location"
    ]


checkbox : Bool -> msg -> String -> Html msg
checkbox b msg name =
  label
    [ style [("padding", "20px")]
    ]
    [ input [ type_ "checkbox", onClick msg, checked b ] []
    , text name
    ]


Seems to work. Then change update to this:

update : Msg -> Model -> Model
update msg model =
  case msg of
    ToggleNotifications ->
      { model | notifications = True } -- instead of { model | notifications = not model.notifications }
    ...
    ...

So although Elm is feeding True to view, the checkbox seems to ignore that input and render its own internal state. So feeding it anything (the current model value or otherwise) does nothing once it is created ... 

Not sure what virtual dom is doing with its diff in these cases, or if this behavior is expected [for any stateful component] and reasonable. Would like to know, though.
Reply all
Reply to author
Forward
0 new messages