在 elm 中为 html 事件链接联合类型

Chaining union types for html events in elm

我不确定这是否可行,但我正在尝试触发具有链式联合类型的 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) ] [] 
]

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

谢谢

它不会工作,因为 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 ] [] 
    ]