Skip to content

Instantly share code, notes, and snippets.

@arsduo
Last active September 28, 2018 20:03
Show Gist options
  • Save arsduo/2bef1129c6d694d7df57fc72e655301c to your computer and use it in GitHub Desktop.
Save arsduo/2bef1129c6d694d7df57fc72e655301c to your computer and use it in GitHub Desktop.
Event logging in Elm
{- Our regularly scheduled update function. -}
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
ourUpdateFunction
{-|
An Elm update function takes a new message and the existing model and returns a tuple of the new model and
any command(s) to be executed, like above. (Using an alias hopefully makes the type signature below clearer.)
-}
type alias UpdateFunctionSignature =
Msg -> Model -> ( Model, Cmd Msg )
{-| This type signature might be confusing at first glance. Here’s what it means:
- a normal update function, that is, a function that takes a message and model and returns a model and commands
- the incoming message
- the existing model
After doing its thing to log that incoming message (and model any model data you want), it then executes and returns the result of the update function as usual.
-}
logMessage : UpdateFunctionSignature -> Msg -> Model -> ( Model, Cmd Msg )
logMessage updateFn msg model =
let
-- our original results
( updatedModel, commands ) =
updateFn msg model
loggingCommand : Cmd Msg
loggingCommand =
-- In the real world, we'd want to do more processing of the messages -- see the next post
-- for a more detailed discussion, including how to handle the fact that Debug.toString
-- is not available in 0.19's optimized mode.
LoggingApi.sendLogEvent (Debug.toString msg)
in
-- Cmd.batch allows us to fire off a logging command alongside any regularly scheduled commands
-- coming out of the update function.
( updatedModel, Cmd.batch [ commands, loggingCommand ] )
{- and finally, our application's main function -}
main =
-- in which the application update function is set up as logMessage wrapping the normal update
Browser.document { update = logMessage update, ... }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment