简体   繁体   English

榆树的翻译模式是什么?

[英]What is the translator pattern in elm?

In the elm git book an architecture is described wherein child components generate messages which are disseminated via the main update function, eventually being handled by the appropriate update function in a child component. Elm git书中 ,描述了一种体系结构,其中子组件生成消息,这些消息通过主更新功能进行传播,最终由子组件中的适当更新功能处理。 How does the translator pattern differ from this and what are the use cases of each pattern. 转换器模式与此有何不同?每种模式的用例是什么? Please provide a simple example. 请提供一个简单的例子。

Whenever you have a nested "component" with an update function, you will need to make sure the parent passes through the child Msgs and Cmds. 只要您具有带有update功能的嵌套“组件”,就需要确保父组件通过子Msgs和Cmds。 The git book outlines this with a simple example (where this code is in the parent, and Widget is the child): git书通过一个简单的示例对此进行了概述 (此代码在父代码中,而Widget是子代码):

type Msg
  = WidgetMsg Widget.Msg

update message model =
  case message of
    WidgetMsg subMsg ->
      let
        ( updatedWidgetModel, widgetCmd ) =
          Widget.update subMsg model.widgetModel
      in
        ( { model | widgetModel = updatedWidgetModel }, Cmd.map WidgetMsg widgetCmd )

The above will be necessary any time a child has an update function. 以上将是必要的任何时候孩子有一个update的功能。 However, the in the above example, the parent never knows or cares what child messages are being communicated to the child. 但是,在上面的示例中,父级从不知道或不在乎正在向该子级传递哪些子级消息。

But now, consider the case that a parent needs to know about a Msg generated by a child. 但是现在,考虑父母需要了解孩子产生的Msg的情况。 For instance: a game where a nested child component needs to communicate with a parent that the game is lost. 例如:一个游戏,其中嵌套的子组件需要与父组件通信,该游戏会丢失。

The Translator Pattern is useful when a parent component needs to react to a message returned from the child update function. 当父组件需要对子更新功能返回的消息做出反应时, 翻译器模式很有用。 Here is the basic structure of the update function in the linked example: 这是链接示例中更新功能的基本结构:

GameMsg internalMsg -> 
  let
    (game_, cmd) 
       = Game.update internalMsg model.game
  in
    { model | game = game_ } ! [ Cmd.map gameTranslator cmd ]

Notice that it looks a lot like the earlier update example; 注意,它看起来很像早期的update示例。 the main difference is that rather than mapping the Cmd directly to a blind parent Msg ( blind in that the single WidgetMsg of the first example only passed around the child Msg ), the gameTranslator mapping function allows you to map to one of the parent messages. 的主要区别在于,而不是映射Cmd直接盲父Msg ,所述单个WidgetMsg第一示例仅围绕子传递的Msg ),则gameTranslator映射函数允许你映射到父消息之一。

It may be helpful to read the Translator Pattern Blog Post in its entirety. 完整阅读《 翻译人员模式博客》可能会有所帮助。 It was written for Elm 0.17 so there are a few syntax changes, but the general idea still holds. 它是为Elm 0.17编写的,因此对语法进行了一些更改,但总体思路仍然成立。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM