Elm 中 onInput 的几个输入和参数

Several inputs and arguments with onInput in Elm

我正在尝试使用 Elm。现在我在屏幕上有几个输入范围,我想单独控制它们的值,但我不知道如何区分它们(在 Js 中我会在 onInput 回调中发送输入的 ID 和 VALUE)因为我只能用 Elm 的 onInput

发送一个参数
inp : Input -> Html Msg
inp inp =
    div [ class "input" ]
        [ p [] [ text inp.name ]
        , input [ id (toString inp.id), type' "range", value inp.volume, onInput ChangeInput ] []
        , controls inp.name inp.id
        ]

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Play id ->
            ( play model id, Cmd.none )

        ChangeInput id value ->
            -- Here I want to grab the id and the value coming from the input --

        NoOp ->
            ( model, Cmd.none )

有什么帮助吗? 谢谢!!

使用部分应用程序:onInput <| ChangeInput inp.id

传递的结果函数现在采用 onInput 预期的单个字符串参数。

您的消息定义应该是:

type Msg =
  ...
  | ChangeInput Id String

这为它提供了 (Id -> String -> Msg) 的签名。 它需要一个 Id 和一个 String 并且它需要 returns 一个 Msg。消息中包含 id 和 string。

您可以通过在您的视图中进行以下更改来提供您自己的附加参数:

onInput (ChangeInput id)

公式(ChangeInput id)是部分应用:

您不提供所有参数,而只提供一个,因此结果将是一个函数,它接受剩余的参数,并输出 Msg 类型。

您已经为消息 (Id -> String -> Msg) 提供了 Id,因此剩余的签名将是 (String -> Msg),这正是 onInput 正在寻找的。

定义联合类型时,您同时定义了:类型注释定义和值构造函数。

type Msg
    = NoOp
    | SomeMessage Int String

联合类型注解定义

在这里您将使用 Msg 来定义函数的类型注释定义,例如:

update: Msg -> Model -> ( Model, Cmd Msg )

联合类型值构造函数

然后您将使用 NoOpSomeMessage 作为 Msg

类型值的构造函数

这里是一个函数的例子,它构造了一个SomeMessage值和returns它:

createSomeMessage: Int -> Msg
createSomeMessage number =
    SomeMessage number "Hello!"

createSomeMessage 1 -- SomeMessage 1 "Hello!"

带有部分应用程序的联合类型值构造函数

Elm 支持部分应用,这意味着,您可以等待 Msg 类型的值的构造,直到您拥有所有必需的参数。

这是它的工作原理:

-- Partially applied value constructor, which expects new argument
messageWithId : String -> Msg
messageWithId =
    SomeMessage 1

{- Later in the view, (SomeMessage 1) will wait for the String from the
   input DOM event
-}
input [ onInput messageWithId ] []

-- Alternative way to express the same thing:

input [ onInput (SomeMessage 1) ] []

上面的示例显示了如何在 DOM 事件触发之前使用值构造函数来应用一些参数。这将生成一条消息,其中包含来自部分应用函数和事件本身的数据。

这里有一个 example 所描述的技术在起作用。