如何将大型Elm程序分成较小的组件 [英] how to divide a large Elm program into smaller components

查看:52
本文介绍了如何将大型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

这篇关于如何将大型Elm程序分成较小的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆