guide.elm-lang.org icon indicating copy to clipboard operation
guide.elm-lang.org copied to clipboard

Incoming Messages section of Ports doesn't talk about Program subscriptions

Open ravicious opened this issue 4 years ago • 0 comments

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 to activeUsers Changed, we will get a Msg 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.

ravicious avatar Nov 02 '19 09:11 ravicious