Skip to content

Instantly share code, notes, and snippets.

@jinjor
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jinjor/e49855410cfac8a2d957 to your computer and use it in GitHub Desktop.
Save jinjor/e49855410cfac8a2d957 to your computer and use it in GitHub Desktop.
How to make a 'stateful' component?
--------------------- Button module
import Html exposing (..)
import Html.Events exposing (..)
import Signal exposing (..)
type ButtonEvent = Increment | NoOp
type alias ButtonState = {
count: Int
}
type alias ButtonComponent = {
state : ButtonState,
mailbox : Mailbox ButtonEvent
}
initialButtonState : ButtonState
initialButtonState = { count = 0 }
buttonSignal' : ButtonComponent -> Signal ButtonComponent
buttonSignal' initialComponent =
let update _ component =
let state = component.state
in {
state = { state | count <- state.count + 1 },
mailbox = component.mailbox
}
in foldp update initialComponent initialComponent.mailbox.signal
buttonSignal : () -> Signal ButtonComponent
buttonSignal _ =
let initialComponent = {state = initialButtonState, mailbox = mailbox NoOp }
in buttonSignal' initialComponent
toHtml : ButtonComponent -> Html
toHtml component = button [
onClick component.mailbox.address Increment
] [
text <| toString component.state.count
]
--------------------- Main
buttonSignal1 = buttonSignal ()
buttonSignal2 = buttonSignal ()
main = (\c1 c2 -> div [] [toHtml c1, toHtml c2]) <~ buttonSignal1 ~ buttonSignal2
@jinjor
Copy link
Author

jinjor commented Jun 14, 2015

paste to Try Elm

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