Correct way of using ports in 0.19


#1

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?


#2

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…


#3

That’s what I’m doing too.


#4

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.


#5

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