【问题标题】:updating model with parameter in elm 0.18使用 elm 0.18 中的参数更新模型
【发布时间】:2017-09-02 23:27:35
【问题描述】:

榆树新手。使用榆树 0.18。

这是一个非常简单的 SPA,有 12 个按钮(每个按钮都有一个音符值)。您单击该按钮,它会显示您单击的注释。

我想通过 onClick 将函数 Put 分配给按钮,然后将字符串参数 note 传递给它,用于更新模型。

这是我的代码:

import Html exposing (div, beginnerProgram, text, button)
import Html.Events exposing (onClick)
import List exposing (..)

main =
  beginnerProgram { model = model, update = update, view = view }

-- model
model =
  { key = "C" }

keys =
  ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]

-- update
type Action = Put

update msg model =
  case msg note of
    Put ->
      { model | key = note }

-- view
makeButton note =
  button [ onClick Put note ] [text note]

view model =
  div [] [
    div [] [text (toString model.key)],
    div [] (map makeButton keys)
  ]

我收到此错误:

-- NAMING ERROR -------------------------------------------------- musiccalc.elm

Cannot find variable `note`

19|   case msg note of

【问题讨论】:

    标签: list functional-programming elm


    【解决方案1】:

    知道了,输入操作,然后在进入onClick 之前先进行评估。

    import Html exposing (div, beginnerProgram, text, button)
    import Html.Events exposing (onClick)
    import List exposing (..)
    
    main =
      beginnerProgram { model = model, update = update, view = view }
    
    -- model
    model =
      { key = "C" }
    
    keys =
      ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
    
    -- update
    type Action =
      Put String
    
    update msg model =
      case msg of
        Put note ->
          { model | key = note }
    
    -- view
    makeButton note =
      button [ onClick (Put note) ] [text note]
    
    view model =
      div [] [
        div [] [text (toString model.key)],
        div [] (map makeButton keys)
      ]
    

    【讨论】:

    • 是的。另外,我认为最好将键设置为type Key = C | C# | D | D# | ... 的联合类型,然后可以将type Action 设置为type Action = Put Key。你怎么看?
    • @gabrielperales Elm 中 TDD 的好例子。类型驱动开发:P 该模型也将是 type Model : Keymodel = C#
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多