Correct way of using ports in 0.19

In 0.19, the code

var elmApp = Elm.Main.init({ node: document.getElementById('app') });
elmApp.ports.somePortName.subscribe(whatever);

breaks if somePortName is declared but not used in the Elm code (I assume that this is due to 0.19’s dead code removal feature).

This actually happened in one of my projects: the same JS module defined two different ports and both were declared Elm-side, but only one was actually used.

If I want my code to be reliable and prevent JS to break unexpectedly, I must add a check to every JS-side port declaration:

elmApp.ports.somePortName && elmApp.ports.somePortName.subscribe(whatever);

This doesn’t seem ideal to me, but seems necessary.
Is this sensible? Am I missing something?

6 Likes

Its worse, I just coded:

app.ports && app.ports.textToSVG &&
  app.ports.textToSVG.subscribe(request => {

To cater for the situation during dev where I have not yet wired up any ports, so app.ports is undefined…

1 Like

That’s what I’m doing too.

The second portion of “Types Without Borders” by Dillon Kearns from elm-conf 2018 tackles this issue using TypeScript. Looks to be a fairly robust solution IMO. Perhaps a bit more overhead initially, but far less pain later.

3 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.