TL;DR
In the previous post, we explored refactoring by moving business logic from the Elm view function. Today we are adding the Comment feature to our Picshare application. This post is part of the functional language series, and it is based on a remarkable book, Programming Elm Build Safe and Maintainable Front-End Applications by Jeremy Fairbank.
Elm Input
Where should we store picture comments? Should we support more than one comment? Elm Model keeps the application state, so we first need to add to the Picshare application model list of previous comments and current comments typed by the user.
First, Elm’s comment in gist explains how to expand the Picshare Model with comments and newComment. If you now try to compile the Picshare application, you would get a compilation error. Move to the second Elm comment will resolve this compilation error.
The third elm comment explains how to display a list of comments. This is done in Elm’s View function. But now we know that each feature should have its own function!
The fourth comment adds a function that adds a list of comments, and it is most complex in this example. First, we check using case
pattern matching if the model list of comments is empty, and in that case we display an empty string. Pattern matching is a functional programming feature. We did not check the length property of the list because that would require traversing the whole list. For larger lists, this slows down your application. _
means for all other comment list values. We add div
with HTML ul
with no attributes but with a list of li
node elements crated with List.map
function. That function takes two arguments, the first is a List, and the second is a function that will be applied to each element of a List. The result is a new List.
The fifth comment adds viewComments
the view function that is using viewCommentList
, and the input is Picshare Model
. We use functions form
, input
and button
to display the comment text input field.
The sixth comment adds to viewDetailedPhoto
view function viewComments
view function that will display comments and input text field below image caption field.
Note that UX looks different. I downloaded main.css
from the book website and fixed typo in viewDetailedPhoto
CSS attribute.
Remember
Divide and conquer, each feature should have dedicated functions. For now, we only display comments.
Comments are closed.