Scott Nimrod
Scott Nimrod

Reputation: 11595

Update function not called on button click

My Update function does not get called after clicking a button (which should send a message).

Here's the code that should trigger the function with the onClick event:

[ input [ type_ "submit", onClick TopicSelected, value (getTopic topic) ] []

Here's the Update function:

update : Msg -> Model -> Model
update msg model =
    case msg of
        TopicSelected ->
            { model
                | articles = []
                , podcasts = []
                , videos = []
            }

view model =
    div []
        [ table []
            [ tr [] [ td [] [ b [] [ text "Videos" ] ] ]
            , div [] <| contentUI model.videos
            , tr [] [ td [] [ b [] [ text "Podcasts" ] ] ]
            , div [] <| contentUI model.podcasts
            , tr [] [ td [] [ b [] [ text "Articles" ] ] ]
            , div [] <| contentUI model.articles
            ]
        ]

Here's the entire function that routes then onClick event:

topicTocheckbox : Topic -> Html Msg
topicTocheckbox topic =
    div []
        [ input [ type_ "submit", onClick TopicSelected, value (getTopic topic) ] []
        , label [] [ text <| getTopic topic ]
        ]

The code can be found on GitHub.

Upvotes: 0

Views: 343

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

Looking at your code, you're trying to use the nested "component" of Contributor.elm in Home.elm, but you aren't wiring things up in the parent (Home) update function.

This is a broad and controversial topic in the Elm community. The typical recommendation is to try to avoid nesting like this unless absolutely necessary.

If you absolutely need to nest in this way, then your code will be sprinkled with variations of update cases like this:

type ParentMsg
    = ...
    | ChildMsg Child.Msg

type alias ParentModel =
    { ...
    , child : Child.Model
    }

case msg of
    ChildMsg childMsg ->
        let (childModel, childCmd) = Child.update childMsg model.child
        in { model | child = childModel } ! [ Cmd.map ChildMsg childCmd ]

At every layer nesting, you'll need to wire up child state and passing child Msg and Cmds back and forth.

Compounded on that is the fact that in your code, you're dealing with a list of Contributors, which means you'll also need to pass around an index so that you know which contributor in the list you're editing (here is a minimal example of updating model array elements).

The good news is that Elm makes refactoring a breeze!

Upvotes: 1

Related Questions