Site icon Bytefreaks.net

An Introduction to Elm Series: Solution to ‘Buttons’ example

Advertisements

In http://guide.elm-lang.org/architecture/user_input/buttons.html, you are given a working code that produces a simple counter which can be incremented or decremented via two buttons on an HTML page.

Your task is to add a new feature to this code, which is to create a new button that will reset the counter. Following you will find a proposed solution to the task. What we did was to create a new message which when received it would zero the model value and then we attached it to a new button we created.

The full solution is as follows and we highlighted all the lines that were added for this additional functionality to work:

import Html exposing (Html, button, div, text)
import Html.App as Html
import Html.Events exposing (onClick)



main =
  Html.beginnerProgram
    { model = model
    , view = view
    , update = update
    }



-- MODEL


type alias Model = Int


model : Model
model =
  0



-- UPDATE


type Msg
  = Increment
  | Decrement
  | Reset


update : Msg -> Model -> Model
update msg model =
  case msg of
    Increment ->
      model + 1

    Decrement ->
      model - 1

    Reset ->
      0

-- VIEW


view : Model -> Html Msg
view model =
  div []
    [ button [ onClick Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick Increment ] [ text "+" ]
    , button [ onClick Reset ] [ text "Reset" ]
    ]

You can download the solution from here [download id=”1791″]

This post is also available in: Greek

Exit mobile version