Elm开始吧
示例
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Trying out ports</title>
</head>
<body>
<div id="app"></div>
<script xx_src="elm.js"></script>
<script>
var node = document.getElementById('app');
var app = Elm.Main.embed(node);
//订阅Elm的消息
app.ports.toJs.subscribe(function(messageFromElm) {
alert(messageFromElm);
//我们可以寄回一些东西
//app.ports.fromJs.send('嘿,收到您的信息!JS,真诚的');
});
//等待三秒钟,然后从JS向Elm发送消息
setTimeout(function () {
app.ports.fromJs.send('Hello from JS');
}, 3000);
</script>
</body>
</html>Main.elm
port module Main exposing (..)
import Html
port toJs : String -> Cmd msg
port fromJs : (String -> msg) -> Sub msg
main =
Html.program
{ init = (Nothing, Cmd.none) -- our model will be the latest message from JS (or Nothing for 'no message yet')
, update = update
, view = view
, subscriptions = subscriptions
}
type Msg
= GotMessageFromJs String
update msg model =
case msg of
GotMessageFromJs message ->
(Just message, toJs "Hello from Elm")
view model =
case model of
Nothing ->
Html.text"No message from JS yet :("
Just message ->
Html.text("来自JS的最后一条消息: " ++ message)
subscriptions model =
fromJs GotMessageFromJselm-lang/html如果尚未安装软件包,请安装elm-packageinstallelm-lang/html--yes。
使用编译此代码,以便HTML文件找到它。elm-makeMain.elm--yes--outputelm.js
如果一切顺利,您应该可以打开index.html显示“无消息”文本的文件。三秒钟后,JS发送一条消息,Elm得到它,更改其模型,发送一个响应,JS得到它并打开警报。