Elm 端口在 Firefox 中不起作用

Elm ports not working in Firefox

我在让 Elm 端口与 Firefox 一起工作时遇到问题。

这是我的 index.html:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Firefox Ports</title>
</head>

<body>
    <script src="/app.js"></script>
</body>

</html>

这是我的 index.js:

"use strict";

require("./index.html");

const Elm = require("./Main.elm");
const app = Elm.Main.fullscreen();
console.log("here");

window.onload = function() {
    console.log("window.onload");
    app.ports.sayHello.subscribe(function(who) {
        console.log("Greetings,", who);
    });
};

这是我的 Main.elm:

port module Main exposing (main)

import Html exposing (Html, div, text)


type Msg
    = None


type alias Model =
    {}


initialModel : Model
initialModel =
    {}


init : ( Model, Cmd Msg )
init =
    ( initialModel, sayHello "Foo" )


port sayHello : String -> Cmd msg


main : Program Never Model Msg
main =
    Html.program
        { init = init
        , update = update
        , subscriptions = subscriptions
        , view = view
        }


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    ( model, Cmd.none )


subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.none


view : Model -> Html Msg
view model =
    div []
        [ text "Hello" ]

在chrome控制台中,输出显示模型初始化时调用了端口函数(init):

11:00:47.320 app.js:9181 here
11:00:47.371 app.js:9184 window.onload
11:00:47.464 app.js:9186 Greetings, Foo

清楚地显示调用了端口函数,但在 Firefox 中,缺少最后一行 (Greetings, Foo):

here
window.onload

我做错了什么?

您可以尝试将 subscribe() 调用移动到 fullscreen() 调用之后,以消除竞争条件的可能性:

const app = Elm.Main.fullscreen();
app.ports.sayHello.subscribe(function(who) {
    console.log("Greetings,", who);
});
console.log("here");

window.onload = function() {
    console.log("window.onload");
};

我的直觉是 Firefox 中的事件循环 运行 Elm 代码 先于 window.onload 在没有订阅端口的时候.这只是一种预感,但我认为最佳做法是您在创建应用后立即设置订阅。