我正在阅读Elm指南及其JavaScript interOp。这是一个简化的版本:
port module FooBar exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.App as Html
import String
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- subscriptions
port f : () -> Cmd msg
port g : ( Int -> msg ) -> Sub msg
subscriptions: Model -> Sub Msg
subscriptions model = g Get
-- MODEL
type alias Model = { pt : Int }
-- VIEW
view: Model -> Html Msg
view model = Html.text ( toString model.pt )
-- UPDATE
type Msg = Ask | Get Int
update: Msg -> Model -> (Model, Cmd msg)
update msg model =
case msg of
Ask -> (model, f () )
Get x -> ( Model x, Cmd.none )
-- INIT
init: (Model, Cmd Msg)
init = ( Model 0, f ())
该应用程序最初设置为0,但应从JavaScript读取消息并设置为1。但是,它保持为0。Elm端口是否设置正确?
<div id="foobar"></div>
<script src="foo.js"></script>
<script>
var node = document.getElementById("foobar");
var app = Elm.FooBar.embed(node);
app.ports.f.subscribe(
function(){
var myValue = 1;
console.log(myValue);
app.ports.g.send(myValue);
}
);
</script>
</body>
我在这里放: elm-make foo.elm --output=foo.js
myValue
打印到控制台为1的事实表明该f()
端口已被调用,但该g()
端口从未被发送回或未正确处理。
很难说这是否是一个设计决定,但是init
在Html.App
订阅任何端口之前被调用。
因此,f ()
从发出呼叫init
将无效。
我使用send
函数,该函数运行一个虚拟任务并始终发送Ask
消息,这将触发传出端口。
考虑更改您init
的发送消息,该消息会将数据发送到端口:
-- INIT
init : ( Model, Cmd Msg )
init =
-- ( Model 0, f ())
( Model 0, send Ask )
send : msg -> Cmd msg
send msg =
Task.perform identity identity (Task.succeed msg)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句