如何将大型Elm程序分成较小的组件

问题描述:

我想将程序的查看和更新部分分成单独的源文件,但是,然后,我如何共享消息和订阅声明?

I'd like to separate the View and Update parts of a program into separate source files, but then, how do I share the Message and Subscriptions declarations ?

在拆分模块之前请三思,过早的代码拆分可能对您的项目有害。

Think twice before splitting your modules, premature code splitting might be harmful to your project.

这里是示例

Html.App.map 允许我们标记子组件的消息,因此可以将其传递给 Components .Counter.Update.update 函数,当键盘订阅发出消息时。

Html.App.map allows us to tag a message for child component, so we could pass it to Components.Counter.Update.update function, when keyboard subscription emits a message.

module App.View exposing (..)

import Html.App
import Html exposing (text, div, Html)
import App.Model exposing (Model)
import App.Messages exposing (..)
import Components.Counter.View


view : Model -> Html Msg
view model =
    div []
        [ Html.App.map Counter (Components.Counter.View.view model.counter) ]



订阅



要标记来自订阅的消息,我们必须使用 Platform.Sub.map

请查看传入 src / App / Subscriptions.elm

module App.Subscriptions exposing (..)

import App.Model exposing (Model)
import App.Messages exposing (..)
import Components.Counter.Subscriptions


subscriptions : Model -> Sub Msg
subscriptions model =
    let
        counterSub =
            Components.Counter.Subscriptions.subscriptions model.counter
    in
        Sub.batch [ Sub.map Counter counterSub ]



文件结构



File structure

Main.elm                 -- Entry point, where App is initialized
Utils.elm                -- Utilities
App/
    Messages.elm
    Model.elm
    Subscriptions.elm
    Update.elm
    View.elm
Components/
    StatefulComponent/
        Messages.elm
        Model.elm
        Subscriptions.elm
        Update.elm
        View.elm
    StatefulComponentWithCommands/
        Commands.elm     -- Functions, which return Cmd msg
        Messages.elm
        Model.elm
        Subscriptions.elm
        Update.elm
        View.elm
    StatelessComponent/
        View.elm