Buda Gavril
Buda Gavril

Reputation: 21637

elm: define subscription port with no parameters

Is there a way to define a subscription port with no parameters in Elm?

Something like:

port updateTime : () -> Sub msg

With this code, I'm getting the error that "Port 'updateTime' has an invalid type"

With the code:

port updateTime : (String -> msg) -> Sub msg

It's working but I don't need to send nothing from the javascript function to Elm.

Upvotes: 10

Views: 1458

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

The closest you can get is probably something like this: Create the port similar to your examples but with the first parameters as (() -> msg):

port updateTime : (() -> msg) -> Sub msg

Assuming you have an UpdateTime Msg that accepts no parameters,

type Msg
    = ...
    | UpdateTime

You can then tie into the updateTime subscription like this:

subscriptions : Model -> Sub Msg
subscriptions model =
    updateTime (always UpdateTime)

Now, on the javascript side, you'll have to pass null as the only parameter.

app.ports.updateTime.send(null);

Update for Elm 0.19

In Elm 0.19 you had to be explicit about which Elm modules exposed ports, so you may have to update your module definition to include port module.

port module Main exposing (main)

Upvotes: 14

Related Questions