2017-09-02 56 views
0

新的榆树。使用榆树0.18。更新模型与参数在榆树0.18

这是一个非常简单的SPA,有12个按钮(每个都有一个音符值)。你点击按钮,它会显示你点击的笔记。

我想通过分配功能Put一个按钮,通过onClick要做到这一点,那么传递的是被用来更新模型中的字符串参数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 

回答

0

得到它,你输入的动作,然后先评估再进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) 
    ] 
+3

是的。另外,我认为如果将键设置为键入类型Key = C |的联合类型会更好C#| D | D#| ...'然后你可以将'type Action'设置为'type Action = Put Key'。你怎么看? – gabrielperales

+0

@gabrielperales榆树TDD的精美例子。类型驱动开发:P 该模型也可以是'type Model:Key'和'model = C#'。 – cDitch