Skip to content

Instantly share code, notes, and snippets.

@maticzav
Created November 29, 2016 15:33
Show Gist options
  • Save maticzav/bb60c437c0b004f5e12c20dd058c30fc to your computer and use it in GitHub Desktop.
Save maticzav/bb60c437c0b004f5e12c20dd058c30fc to your computer and use it in GitHub Desktop.
Allows you to send new state to JS every time state is changed in Elm program.
withOnStateChangeSub : (model -> Cmd msg) -> (msg -> model -> ( model, Cmd msg )) -> msg -> model -> ( model, Cmd msg )
withOnStateChangeSub statePort update msg model =
let
( updatedModel, cmd ) =
update msg model
updatedCmd : Cmd msg
updatedCmd =
if updatedModel == model then
cmd
else
Cmd.batch [ statePort updatedModel, cmd ]
in
( updatedModel, updatedCmd )
-- Use
port statePort : Model -> Cmd msg
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
...
main =
program
{ ...
, update = withOnStateChangeSub statePort update
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment