【问题标题】:Locally scoped updates in elm 0.18elm 0.18 中的本地范围更新
【发布时间】:2017-09-13 20:10:32
【问题描述】:

我有一个 elm 0.18 网络应用程序,其中包含许多页面和路线。在main.elm 中我定义了我的更新函数。

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

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

例如,我有一个设置页面,让用户能够更改密码。三个字段/状态(passwordOld、passwordNew、passwordConfirm)具有与onInputonBlur 事件关联的更新操作。这些状态和动作只与用户设置页面相关,当用户离开页面时,与模型的其余部分无关。

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

【问题讨论】:

标签: elm


【解决方案1】:

您可以将代码分解为独立的子模块,每个子模块都有自己的 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)
        ]

这样,与您的子模块相关的所有信息和状态都封装在您的子模块中,并且您的主更新函数中只有一个案例负责正确路由消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    相关资源
    最近更新 更多