Skip to content

Instantly share code, notes, and snippets.

@savuori
Last active December 3, 2015 16:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save savuori/a54ea0d27dc2007b1950 to your computer and use it in GitHub Desktop.
Save savuori/a54ea0d27dc2007b1950 to your computer and use it in GitHub Desktop.
module InputWithAddAction (Model, Action, view, update, init) where
import Html exposing (div, input, button, text)
import Html.Events exposing (onClick, on, targetValue)
import Html.Attributes exposing (value)
import Signal
type Action = UpdatedValue String
type alias Model = String
init : Model
init = ""
update : Action -> Model -> Model
update action model =
case action of
UpdatedValue str
-> str
{- the first parameter here is the callback -}
view addAction address model =
div []
[ input
[ value model
, on "input" targetValue (Signal.message address << UpdatedValue)
]
[]
, button
[ on "click" targetValue (addAction model) ]
[ text "Add to list" ]
]
module Main where
import Html exposing (div, text, ul, li, Html)
import InputWithAddAction
type Action = Add String | Delete String | InputAction InputWithAddAction.Action | NoOp
--- MODEL ---
type alias Model =
{ stuffList : List String
, inputModel : InputWithAddAction.Model
}
-- initial model
init : Model
init =
{ stuffList = ["initial", "stuff"]
, inputModel = InputWithAddAction.init
}
-- mailbox of actions
actions = Signal.mailbox NoOp
update : Action -> Model -> Model
update action model =
case action of
Add str
-> { model | stuffList = str :: model.stuffList }
Delete str
-> { model | stuffList = (List.filter ((/=) str) model.stuffList) }
InputAction act
-> { model | inputModel = (InputWithAddAction.update act model.inputModel) }
NoOp -> model
view : Model -> Html
view model =
div []
[ (InputWithAddAction.view
{- here we construct a function that the child view can use to
send actions to parent -}
(\textToAdd _ -> Signal.message actions.address (Add textToAdd))
(Signal.forwardTo actions.address InputAction)
model.inputModel)
, ul []
(List.map (\m -> li [] [text m]) model.stuffList)
]
signals = Signal.foldp update init actions.signal
main : Signal Html
main = Signal.map view signals
@fredcy
Copy link

fredcy commented Dec 2, 2015

The callback is interesting. I'd remove the ignored second parameter and invoke it as (always (addAction model)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment