-
-
Save halfzebra/89197bc6111e0797d1105eec5a589374 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment