guide.elm-lang.org
guide.elm-lang.org copied to clipboard
Incoming Messages section of Ports doesn't talk about Program subscriptions
Please fill in the following information:
- My programming background is doing Ruby for the last 10 years and writing apps in Elm for the past 3.
- I want to learn Elm because I forgot how I'm supposed to setup ports.
- I was confused by lack of information about the
subscriptions
function of Program.
I didn't touch ports in a long time and wanted to remind myself how they're supposed to be set up. I went to the Ports guide and was able to create a port for outgoing messages pretty easily.
However, the section about incoming messages left me confused. The section only shows this code:
On the Elm side, this means defining the port like this:
port module Main exposing (..) import Json.Encode as E type Msg = Searched String | Changed E.Value port activeUsers : (E.Value -> msg) -> Sub msg
And then it says:
It creates a
activeUsers
function, and if we subscribe toactiveUsers Changed
, we will get aMsg
whenever folks send values in from JavaScript.
"If we subscribe" does some heavy lifting here without saying how we're actually supposed to subscribe to that port. I thought I'm supposed to only write the code from that one code block and this left me confused. I couldn't understand how Elm is supposed to know which message to send to my update function.
I did some googling and found the post from thoughtbot which helped me realize I also need to have subscriptions
function in my Program and I need to add my port there.
I think it'd be beneficial to show the definition of the subscriptions
function in the example and how it fits into the Program created by the Browser module.