Multiple inputs and arguments with onInput in Elm

I'm experimenting a bit with Vyazh. Now I have several input ranges on the screen, and I want to individually control their values, but I don’t know how to distinguish between them (in Js I sent the identifier and VALUE of the input to the onInput callback), since I can send only one argument using 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 )

Any help? Thank!!

+4
source share
3 answers

The definition of your message should be:

type Msg =
  ...
  | ChangeInput Id String

This gives him a signature (Id -> String -> Msg). it takes Ida Stringand returns a Msg. And the message includes id and string.

You can specify your own additional arguments by making the following changes to your view:

onInput (ChangeInput id)

(ChangeInput id) :

, , , Msg.

Id (Id -> String -> Msg), (String -> Msg), onInput.

+4

Union, : .

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!"

Union

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 .

+1

Use partial application: onInput <| ChangeInput inp.id

Now the function passed takes one string argument, expected onInput.

0
source

Source: https://habr.com/ru/post/1660051/


All Articles