elm 0.18

时间:2017-09-13 05:14:06

标签: elm

我有一个带有多个页面和路线的elm 0.18网络应用程序。在main.elm我定义了我的更新功能。

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        FirstUpdateAction ->
    ...

每一个动作都经过这个功能而且变得越来越大。是否可以为嵌套在整体结构中的较小模块创建更新功能?

例如,我有一个设置页面,可让用户更改密码。有三个字段/状态(passwordOld,passwordNew,passwordConfirm),它们具有与onInputonBlur事件关联的更新操作。这些状态和操作仅与用户设置页面相关,并在用户离开页面时对模型的其余部分无效。

我如何设置用户设置的范围?

1 个答案:

答案 0 :(得分:2)

您可以将代码分解为独立的子模块,每个子模块都有自己的Msg类型,更新和查看功能。

例如,您可以将文件SubmoduleA.elm看起来像这样:

module SubmoduleA exposing (Model, Msg, update, view)

type Msg = SubMessageA 
         | SubMessageB

         [..]

type alias model = 
    { fieldA : TypeA
    ,  fieldB : TypeB
    ,  [..]
    }

update msg model = 
  case msg of 
    MessageA -> 
        {model | fieldA = [..] } ! []
    [..]

view model = 
    div [id "submoduleAView"]
        [..]

此模块将连接到您的主程序,如下所示:

module Main exposing (..)

import SubmoduleA exposing (Model, Msg, update, view)

type Msg = MessageA 
         | MessageB
         | ToSubmoduleA (SubmoduleA.Msg)
         [..]

type alias model = 
    { fieldA : TypeA
    , fieldB : TypeB
    , [..]
    , subModuleA : SubmoduleA.Model
    }

update msg model = 
  case msg of 
    MessageA -> 
        {model | fieldA = [..] } ! []

    [..]

    ToSubmoduleA msg = 
        let (newSubmoduleA, newSubmoduleACmd) = SubmoduleA.update msg (.subModuleA model)
        in { model | subModuleA = newSubmoduleA } ! [Cmd.map ToSubmoduleA newSubmoduleACmd]

view model = 
    div [id "mainView"]
        [ ..
        , Html.map ToSubmoduleA <| SubmoduleA.view (.subModuleA model)
        ]

这样,与子模块相关的所有信息和状态都保存在子模块中,并且主要更新功能中只有一个案例负责正确的消息路由。

相关问题