如何为动态生成的复选框定义消息?
topicTocheckbox : Topic -> Html Msg
topicTocheckbox topic =
div []
[ input [ type_ "checkbox", name "topic", onClick TopicSelected, value <| getTopic topic ] []
, label [] [ text <| getTopic topic ]
]
我更容易对消息的附加数据进行模式匹配。在我的情况下,我会将主题附加到TopicSelected联合案例。
因此,我希望我能定义这样的信息:
type Msg
= TopicSelected topic
然而,这并不与example that I am referencing对齐。
以下是如何生成复选框:
topicsUI : List Topic -> Html Msg
topicsUI topics =
let
formattedTopics =
topics |> List.map topicTocheckbox
in
Html.form [ action "" ] formattedTopics
答案 0 :(得分:4)
您可以为TopicSelected
提供一个参数。在您链接的示例中,您引用了此Msg
定义:
type Msg
= ToggleNotifications
| ToggleAutoplay
| ToggleLocation
您可以将其重写为具有Toggle
类型的单个Target
消息:
type Target
= Notifications
| Autoplay
| Location
type Msg
= Toggle Target
然后,您可以按update
模式匹配每个变体:
update : Msg -> Model -> Model
update msg model =
case msg of
Toggle Notifications ->
{ model | notifications = not model.notifications }
Toggle Autoplay ->
{ model | autoplay = not model.autoplay }
Toggle Location ->
{ model | location = not model.location }
beginnerProgram示例中此新定义的视图如下所示:
checkbox (Toggle Notifications) "Email Notifications"
这很好地转化为您的Topic
示例。根据{{1}}的定义方式,您可以执行以下操作:
Topic
您的type Topic
= Math
| Literature
| Music
type Msg
= TopicSelected Topic
可能如下所示:
onClick
,您的更新可以通过模式匹配指定每个主题:
onClick (TopicSelected topic)