榆树:父通过端口更新子组件

时间:2016-10-02 05:07:23

标签: elm

父组件是否可以将其传入端口的结果传递给子组件。

我一直在研究这个组成父/子组件(https://www.elm-tutorial.org/en/02-elm-arch/06-composing.html)的例子。这个例子很棒 - 但我想通过Ports更新孩子的模型。这可能吗?

Example Gist

index.js

var num = 0;
setInterval(function () {
  num = num + 1
  app.ports.tick.send(num)
},1000);

Ports.elm

port module Ports exposing (..)

port tick : (Int -> msg) -> Sub msg

Main.elm(父母)

import Widget

type Msg
    = WidgetMsg Widget.Msg


update : Msg -> AppModel -> ( AppModel, Cmd Msg )
update message model =
    case message of
        WidgetMsg subMsg ->
            let
                ( updatedWidgetModel, widgetCmd ) =
                    Widget.update subMsg model.widgetModel
            in
                ( { model | widgetModel = updatedWidgetModel }, Cmd.map WidgetMsg widgetCmd )


subscriptions : AppModel -> Sub Msg
subscriptions model =
    Ports.tick WidgetMsg

Widget.elm(儿童)

initialModel : Model
initialModel =
    { count = 0
    , tickValue = 0
    }


type Msg
    = Increase
    | Tick Int


update : Msg -> Model -> ( Model, Cmd Msg )
update message model =
    case message of
        Increase ->
            ( { model | count = model.count + 1 }, Cmd.none )

        Tick val ->
            ({model | tickValue = val}, Cmd.none)

1 个答案:

答案 0 :(得分:2)

您需要指定Msg从端口接收int值的子节点。如果您将父订阅功能更新为此,它将发送Widget Tick消息:

Ports.tick (WidgetMsg << Widget.Tick)