Skip to content

Instantly share code, notes, and snippets.

@permelin
Last active September 23, 2015 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save permelin/f1b70d45042cb8881d50 to your computer and use it in GitHub Desktop.
Save permelin/f1b70d45042cb8881d50 to your computer and use it in GitHub Desktop.
import Html exposing (..)
import Html.Attributes
import Html.Events exposing (onClick)
import Signal
-- ACTIONS
type Action = Increment
| Decrement
| None -- The mailbox needs a default
defaultAction = None
-- MODEL
type alias Model = Int
initialModel = 0
updateModel : Action -> Model -> Model
updateModel action model =
case action of
Increment -> model + 1
Decrement -> model - 1
-- VIEW
viewMailbox : Signal.Mailbox Action
-- The view gets its own mailbox. The view sends actions to the mailbox's
-- address, and others can hook into the mailbox's signal.
viewMailbox =
Signal.mailbox defaultAction -- Create and return mailbox
renderView : Model -> Html
renderView model =
let
address = viewMailbox.address -- Where we send actions (events) that
-- should update the model
in
div []
[ button [ onClick address Decrement ] [ text "-" ]
, div [ counterStyle ] [ text (toString model) ]
, button [ onClick address Increment ] [ text "+" ]
]
counterStyle : Html.Attribute
counterStyle =
Html.Attributes.style
[ ("font-size", "20px")
, ("font-family", "monospace")
, ("display", "inline-block")
, ("width", "50px")
, ("text-align", "center")
]
-- SIGNALS
--
-- The flow: viewSignal => modelSignal => htmlSignal
viewSignal : Signal Action
-- Signal that carries actions from the view.
viewSignal =
viewMailbox.signal
modelSignal : Signal Model
-- Signal that carries the updated model state after changes that comes
-- from the view's mailbox's signal are applied.
modelSignal =
Signal.foldp -- Returns a new signal
updateModel -- Function to update the state
initialModel -- Starting value for the model
viewSignal -- Signal with actions that trigger update
htmlSignal : Signal Html
-- Signal that carries the updated HTML after state has changed.
htmlSignal =
Signal.map renderView modelSignal -- Maps a signal of model state to
-- a signal of HTML
-- MAIN
main : Signal Html
main =
htmlSignal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment