如何为动态生成的复选框定义消息?

How do I define messages for checkboxes that are dynamically generated?

如何为动态生成的复选框定义消息?

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

你可以给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 示例。根据 Topic 的定义方式,您可以这样做:

type Topic
    = Math
    | Literature
    | Music

type Msg
    = TopicSelected Topic

您的 onClick 可能如下所示:

onClick (TopicSelected topic)

并且您的更新可以通过模式匹配指定每个主题:

update msg model =
  case msg of
    TopicSelected Math ->
      model

    TopicSelected Literature ->
      model
    ...