Last active
June 28, 2016 02:19
-
-
Save boxxxie/bd1de0136404816400f5f56aaa776ee0 to your computer and use it in GitHub Desktop.
this isn't the most basic. as it is showing how to use commands in the update function, and thus can't be used with HTML.beginnerProgram. this is an extension from the egghead todo list tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Html.App as Html | |
import Html.Events exposing (onInput, onClick) | |
import String exposing (..) | |
import Random exposing (..) | |
main = | |
Html.program | |
{ | |
init = init, | |
update = update, | |
view = view, | |
subscriptions = subscriptions | |
} | |
-- SUBSCRIPTIONS | |
subscriptions : Model -> Sub Msg | |
subscriptions model = | |
Sub.none | |
type alias Model = | |
{ | |
newLabel: String, | |
todos: List TodoItem | |
} | |
type alias TodoItem = | |
{ | |
id: Int, | |
label: String | |
} | |
model = { | |
newLabel = "", | |
todos = [] | |
} | |
init = (model, Cmd.none) | |
type Msg = | |
UpdateText String | |
| AddItem Int | |
| AddNewItem | |
| RemoveItem Int | |
todoIdGenerator = | |
Random.int 0 maxInt | |
update msg model = | |
case msg of | |
UpdateText text -> | |
({ model | newLabel = text }, Cmd.none) | |
--this is just to generate the id for the list item... | |
AddNewItem -> | |
(model, Random.generate AddItem todoIdGenerator) | |
AddItem id -> | |
({ model | todos = { | |
label = model.newLabel, | |
id = id | |
} :: model.todos | |
}, Cmd.none) | |
RemoveItem idToRemove -> | |
({ | |
model | | |
todos = | |
List.filter (\{id} -> id /= idToRemove ) model.todos | |
}, Cmd.none) | |
todoItem todo = | |
li [] | |
[ | |
div [] [ | |
text ((toString todo.id) ++ " " ++ todo.label), | |
--This maybe should be handled in the removeItem update case | |
button [ onClick (RemoveItem todo.id) ] [ text "X" ] | |
]] | |
todoList todos = | |
ul [] (List.map todoItem todos) | |
view model = | |
div [] | |
[ | |
input [ type' "text", | |
onInput UpdateText, | |
value model.newLabel | |
] [], | |
button [ onClick AddNewItem ] [ text "add todo" ], | |
todoList model.todos | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment