在不使用任务的情况下从组件调用更新功能

Call update function from component without using task

我有一个带有主应用程序和组件的榆树项目。

我希望组件有自己的内部更新,并且还能够更新主模型。

我希望组件的 update 函数能够 运行 一个 Cmd 将数据传递给主应用程序并更改主应用程序 url。

我发现能够做到这一点的唯一方法是使用 Task.performTask.succeed

不使用 Task.performTask.succeed 是否可以做到这一点? 在这种情况下使用 Task.performTask.succeed 模式有什么负面影响?

简答:

在您的父模型中,存储子模型的副本。并在parents的update方法中,处理child的消息,调用child的update函数。即:

--In Parent
type alias ParentModel = {
    childModel : ChildModel
}

Type Msg 
    = ChildMsg Child.Msg

case ParentMsg parentMsg ->
    let
        ( newChildModel, childMsg ) =
            Child.update parentMsg model.childModel
    in
        ( { model | childModel = newChildModel }, Cmd.map ParentMsg childMsg )

view model =
    Html.map ParentMsg (Child.view model.childModel)
    ...

长答案: 父子关系更像是一种面向对象的编程风格,这在函数式语言中很难做到。正如函数式编程在面向对象语言中很难做到一样。使用该语言的设计方式要容易得多。如果您对如何以函数式风格组织代码更感兴趣,请查看 Richard Feldmans Scaling Elm video or if you are interested in organizing code across multiple pages in an elm app, check out this example git repo Richard created