我正在与榆树进行一些实验。现在我在屏幕上有几个输入范围,我想单独控制它们的值,但我不知道如何区分它们(在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 )
有任何帮助吗? 谢谢!
答案 0 :(得分:6)
您的邮件定义应为:
type Msg =
...
| ChangeInput Id String
这给它一个(Id -> String -> Msg)
的签名。
它需要Id
和String
,并返回Msg
。消息包括id和string。
您可以通过在视图中进行以下更改来提供自己的其他参数:
onInput (ChangeInput id)
公式(ChangeInput id)
是部分申请:
您不提供所有参数,只提供一个,因此结果将是一个函数,它接收剩余的参数,并输出Msg
类型。
您已在邮件Id
上提供了(Id -> String -> Msg)
,因此其余签名将为(String -> Msg)
,这是onInput
正在寻找的内容。
答案 1 :(得分:2)
定义联合类型时,可以同时定义:类型注释定义和值构造函数。
type Msg
= NoOp
| SomeMessage Int String
在这里,您将使用Msg
为以下函数定义类型注释定义:
update: Msg -> Model -> ( Model, Cmd Msg )
然后,您将使用NoOp
和SomeMessage
作为Msg
这是一个函数示例,它构造一个SomeMessage
值并返回它:
createSomeMessage: Int -> Msg
createSomeMessage number =
SomeMessage number "Hello!"
createSomeMessage 1 -- SomeMessage 1 "Hello!"
Elm支持Partial Application,这意味着,您可以等待构造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。
答案 2 :(得分:1)
使用部分申请:onInput <| ChangeInput inp.id
现在传递的结果函数接受onInput
所期望的单个字符串参数。