In this workshop, we will be implementing some features using existing code as scaffolding.
- Make a button that adds a furby to the shopping cart
- Increment and Decrement the quantity of furbies in the line item
- Calculate the current cart total
- Embed a dropdown component for selecting a pet
- Delete a line item
Review the entry point Main.elm
Then take a look at the Model for our application here src/kit/Model.elm
First notice Add
in the Msg
union type in src/kit/Msg.elm
We need the system to handle new Add
messages. Add
messages contain a Pet
as defined in our Model.
To make this work, we will need to do 2 things
- Put the add button into the
view
function, by using the button component, such that it sendsAdd Furby
when clicked. - Handle incoming
Add
messages in theupdate
function, by updating themodel
with a newLineItem
as defined in our Model.
Since we already have the cart list wired up to the view, we should be able to add some furbies!
Lets allow the user to increment and decrement the quantity of furbies in the cart. These new actions, just like Add
, are going to be messages that flow through the system. To make increment and decrement work is very similar to the process we just went through.
- Document these new messages on our
Msg
type. - Add
onClick
event listeners to the increment and decrement buttons in the view, that send the messages of typeMsg
. - Handle the new messages in the
update
function, such that the model of the cart is updated appropriately.
The total is not a new message, nor does it belong in the model (since it can be derived from the model). So, for the purposes of this exercise we'll put the computation of the total in the view.
Now that you've seen how the 5 core parts of The Elm Architecture pattern fit together, lets embed a component into the system. This project has been prepped with a simple dropdown component. Sub-components being made from the same 5 parts (or less as needed), is a double-edged sword.
- On the one side, it provides an extreme level of flexibility, modularity, and code reuse.
- On the other side, it means wiring in a rich component potentially means touching all 5 core parts of the parent application to route stateful-ness to the sub-component.
... you can do it, give it shot ...