Buttons
I included the full program below. Click the blue “Edit” button to mess with it in the online editor. Try changing text on one of the buttons. Click the blue button now!
Now that you have poked around the code a little bit, you may have some questions. What is the value doing? How do the different parts fit together? Let’s go through the code and talk about it.
The main
value is special in Elm. It describes what gets shown on screen. In this case, we are going to initialize our application with the init
value, the view
function is going to show everything on screen, and user input is going to be fed into the update
function. Think of this as the high-level description of our program.
Data modeling is extremely important in Elm. The point of the model is to capture all the details about your application as data.
To make a counter, we need to keep track of a number that is going up and down. That means our model is really small this time:
type alias Model = Int
The initial value is zero, and it will go up and down as people press different buttons.
We have a model, but how do we show it on screen? That is the role of the view
function:
view : Model -> Html Msg
view model =
div []
, div [] [ text (String.fromInt model) ]
, button [ onClick Increment ] [ text "+" ]
This function takes in the Model
as an argument. It outputs HTML. So we are saying that we want to show a decrement button, the current count, and an increment button.
Notice that we have an onClick
handler for each button. These are saying: when someone clicks, generate a message. So the plus button is generating an Increment
message. What is that and where does it go? To the update
function!
The update
function describes how our Model
will change over time.
We define two messages that it might receive:
From there, the update
function just describes what to do when you receive one of these messages.
update : Msg -> Model -> Model
update msg model =
case msg of
Increment ->
model + 1
model - 1
So whenever we get a message, we run it through update
to get a new model. We then call view
to figure out how to show the new model on screen. Then repeat! User input generates a message, update
the model, view
it on screen. Etc.
Now that you have seen all the parts of an Elm program, it may be a bit easier to see how they fit into the diagram we saw earlier:
Elm starts by rendering the initial value on screen. From there you enter into this loop:
- Wait for user input.
- Send a message to
update
- Produce a new
Model
- Call
view
to get new HTML - Show the new HTML on screen
- Repeat!
This is the essence of The Elm Architecture. Every example we see from now on will be a slight variation on this basic pattern.
Exercise: Add a button to reset the counter to zero:
- Add a
Reset
variant to theMsg
type- Add a
Reset
branch in the functionYou can edit the example in the online editor .