【问题标题】:Chaining union types for html events in elm在 elm 中为 html 事件链接联合类型
【发布时间】:2018-07-03 07:42:33
【问题描述】:

我不确定这是否可行,但我正在尝试使用链式联合类型触发 html 事件。我有以下两种联合类型:

type DialogOf =
    SearchItems
    | SearchingItems String
    | None

type Msg = 
    Start
    | ShowDialog DialogOf
    | CancelDialog

我按如下方式处理模型更新,效果很好。

        ShowDialog dialogOf ->
            case dialogOf of
                SearchItems ->
                    ( { model | dialogOf = SearchItems }, Cmd.none)
                SearchingItems filter -> 
                    ( {model | context = CurrentContext filter }, Cmd.none )
                None -> (model ,Cmd.none)

现在,当我触发事件时,我想使用过滤器(字符串)触发 SearchingItems,这可以使用按钮的 onClick 来完成:

let searchWordButton item = 
    div [] [ 
        button [ onClick (ShowDialog (SearchingItems item))] [text item]
    ]

现在我想触发文本框的 onInput 以过滤文本输入,但我找不到任何方法来使用隐式传递的值来执行此操作 - 我正在尝试做这样的事情(不工作):

div [] [ input [ 
    value model.context.filter, onInput (ShowDialog SearchingItems) ] [] 
]

我意识到可能有其他更好的方法来处理这个问题(如sub modules),但我想知道是否有一种方法可以使用上面的链式联合类型通过 onInput 事件隐式传递字符串值?

谢谢

【问题讨论】:

  • 您尝试向应用程序添加哪些功能导致您走上了这条道路?
  • 我需要在一个已经很忙的表单中添加多个对话框,但我认为这可能是简化 Msg / update 而不是拥有大量 Msg 类型的好方法。我想我必须改用子模块。
  • 也许您应该退后一步,重新考虑用户体验。重新设计界面以减少表单上的噪音并消除对多个对话框的需要。这可能不是需要用代码修复的问题。

标签: elm


【解决方案1】:

因为 ShowDialogue 的类型是

,所以它不起作用
(DialogueOf -> Msg)

但 onInput 需要一个类型为

的参数
(String -> Msg)

换句话说,onInput 将字符串传递给消息 (ShowDialogue) 而不是构造函数 SearchingItems。

我不相信有办法只访问字符串(然后您可以将它直接传递给 SearchingItems)。如果您想更深入地了解,可以考虑使用 on (http://package.elm-lang.org/packages/elm-lang/html/2.0.0/Html-Events#on) 制作自定义事件侦听器,但我认为它不会起作用,而且似乎有点矫枉过正。

您最好使用两条不同的消息来捕获不同的用途:

type Msg 
    = Start
    | ShowDialog DialogOf
    | ShowDialogWithString String
    | CancelDialog

更新函数:

    ShowDialog dialogOf ->
        ( { model | dialogOf = SearchItems }, Cmd.none)

    ShowDialogWithString filter -> 
        ( {model | context = CurrentContext filter }, Cmd.none )

查看

div [] 
    [ input 
        [ value model.context.filter, onInput ShowDialogWithString ] [] 
    ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    相关资源
    最近更新 更多