gpt4 book ai didi

javascript - 连接端口和订阅时遇到问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:31:59 24 4
gpt4 key购买 nike

我正在通读 Elm guide和他们的 JavaScript 互操作。这是一个简化版本:

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() 端口永远不会被发回或正确处理。

最佳答案

很难判断这是否是设计决定,但是在 Html.App 订阅任何端口之前调用了 init

因此从init调用f()将没有效果。

我使用 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)

关于javascript - 连接端口和订阅时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37586991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com