【问题标题】:How to decode html-input to int in Elm?如何在 Elm 中将 html-input 解码为 int?
【发布时间】:2016-04-04 11:24:04
【问题描述】:

有 html 输入。我们监听输入事件并更新模型(这里是简单的字符串)。现在我想对模型使用 Int 类型,并从输入的值中解析 Int 。我制作了另一个解码器并将初始模型的值更改为 0。在这些更改之后,当我输入数字时模型不会改变。为什么?如何实现?

import Html exposing (input, div, text)
import Html.Events
import StartApp.Simple
import Json.Decode

model = ""

view address model =
  let

    decoder =
      Html.Events.targetValue

    -- this decoder doesn't work
    decoderInt =
      Json.Decode.at ["target", "value"] Json.Decode.int

  in
    div [] [
      input [ Html.Events.on "input" decoder (Signal.message address) ] [],
      text (toString model)
    ]

update action model =
  action

main =
  StartApp.Simple.start { model = model, view = view, update = update }

【问题讨论】:

    标签: parsing input decode elm


    【解决方案1】:

    Json 解码不起作用,因为 Json 值是一个字符串,即使字符串中的值是一个数字。例如,Json 值如下所示:

    { "target": { "value": "42" } }
    

    Elm 的 Json 解码函数非常严格,因此它们会将"42" 视为仅仅是一个字符串。您需要进一步构建一个解码器,将该字符串的内部解析为数字 - 如果用户键入非数字的内容,这一行为可能会失败。

    为此,我们可以切换回最初使用Html.Events.targetValue 解码器,因为它知道如何解码字符串值。然后我们将其传递给Json.Decode.andThen 以提取该字符串的值并对其进行操作。

    decoderInt =
      Html.Events.targetValue `Json.Decode.andThen` \str ->
        case String.toInt str of
          Ok i ->
            Json.Decode.succeed i
          Err msg ->
            Json.Decode.fail msg
    

    使用succeedfail 将值映射回Decoder Int 的类型。

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多