Skip to content

Instantly share code, notes, and snippets.

@evancz
Last active March 21, 2019 17:37
Show Gist options
  • Save evancz/8521339 to your computer and use it in GitHub Desktop.
Save evancz/8521339 to your computer and use it in GitHub Desktop.
Example usage of Elm "ports" that uses signals, non-signals, records, and tuples. Build the Elm code with "elm --only-js Shanghai.elm" and include all of the JS in the HTML document.
// initialize the Shanghai component which keeps track of
// shipping data in and out of the Port of Shanghai.
var shanghai = Elm.worker(Elm.Shanghai, {
coordinates:[0,0],
incomingShip: { name:"", capacity:0 },
outgoingShip: ""
});
function logger(x) { console.log(x) }
shanghai.ports.totalCapacity.subscribe(logger);
// send some ships to the port of Shanghai
shanghai.ports.incomingShip.send({
name:"Mary Mærsk",
capacity:18270
});
shanghai.ports.incomingShip.send({
name:"Emma Mærsk",
capacity:15500
});
// have those ships leave the port of Shanghai
shanghai.ports.outgoingShip.send("Mary Mærsk");
shanghai.ports.outgoingShip.send("Emma Mærsk");
module Shanghai where
import Either (..)
import Dict
port coordinates : (Int,Int)
port incomingShip : Signal { name:String, capacity:Int }
port outgoingShip : Signal String
ships = merge (Right <~ incomingShip) (Left <~ outgoingShip)
updateDocks ship docks =
case ship of
Right {name,capacity} -> Dict.insert name capacity docks
Left name -> Dict.remove name docks
dock = foldp updateDocks Dict.empty ships
port totalCapacity : Signal Int
port totalCapacity = lift (sum . Dict.values) dock
<html>
<head>
<title>Embedding Elm in HTML!</title>
<script type="text/javascript" src="http://elm-lang.org/elm-runtime.js"></script>
<script type="text/javascript" src="build/Shanghai.js"></script>
</head>
<body>
<h1>Ports of Shanghai</h1>
<p>Check out the developer console. Try sending values to <code>shanghai.ports.incomingShip</code>.</p>
</body>
<script type="text/javascript" src="Ports.js"></script>
</html>
@shamansir
Copy link

I messed up my example, sorry, @peerreynders yours is awesome!

@cdaringe
Copy link

what's not clear to me in the docs or this example is when you have a Main "app" already, but then want to add a port module within that existing app. That is to say, all of the examples i've yet seen are as though the port module is also the entrypoint itself

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment