简化按钮,单击时更改布尔值

时间:2015-12-05 11:01:12

标签: elm

我创建了一个包含布尔值的按钮,当您单击它时,它会更改此值和按钮内的文本。下面的代码有效,但我有一种感觉,我做了一个矫枉过正的事。如何编写此按钮尽可能简单但仍遵循ELM架构?

module BtnPin where

import Html exposing ( Html )
import Html.Events as E
import StartApp.Simple as StartApp

-- MAIN

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

-- MODEL

type alias Model =
    {pinned : Bool}

init : Model
init = Model False

emptyModel : Model
emptyModel =
    { pinned = False
    }

pin : Model -> Model
pin model =
    if model.pinned then
        Model False
    else
        Model True

viewPin : Signal.Address Action -> Model -> Html
viewPin address model =
    if model.pinned == True then
        Html.button
            [ E.onClick address Pin ]
            [ Html.text <| "Unpin" ]
    else
        Html.button
            [ E.onClick address Pin ]
            [ Html.text <| "Pin" ]

-- UPDATE

type Action = Pin 

update : Action -> Model -> Model
update action model =
  pin model 

-- VIEW

view : Signal.Address Action -> Model -> Html
view address model =
    Html.div []
    [ viewPin address model ]

1 个答案:

答案 0 :(得分:1)

你越明确,越接近榆树建筑,就越容易为知道模式的人阅读。它也很容易扩展。但是,您当然可以简化您不希望发生变化的组件。

请记住,使用您在问题中的代码,您需要的唯一文档是单句描述,因为代码是Elm Architecture,所有内容都有类型注释并且非常简单。压缩代码时,可能需要更多文档。

简化按钮:

module BtnPin where

import Html exposing ( Html )
import Html.Events as E
import StartApp.Simple as StartApp

main =
  StartApp.start { model = False, view = view, update = always not }

-- VIEW

view : Signal.Address () -> Bool -> Html
view address model =
  Html.div [] [ viewPin address model ]

viewPin : Signal.Address () -> Bool -> Html
viewPin address model =
  let
    text = if model then "Unpin" else "Pin"
  in
    Html.button
      [ E.onClick address () ]
      [ Html.text text ]

这可能有点极端,因此您可以通过定义update函数,Model类型和Action类型来妥协。但是那时你已经非常接近你开始的地方......