榆树端口在Firefox中不起作用

时间:2017-11-13 16:12:09

标签: firefox elm

我在让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

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您可以尝试在调用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。这只是一种预感,但我认为最佳实践要求您在创建应用程序后立即设置订阅。