From 174137e825c7f696586c0a5d9a17e4329b508b3d Mon Sep 17 00:00:00 2001 From: bashbunni Date: Thu, 17 Aug 2023 11:03:09 -0700 Subject: [PATCH] docs: how to handle events in a specific model --- tutorials/patterns/README.md | 41 ++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 tutorials/patterns/README.md diff --git a/tutorials/patterns/README.md b/tutorials/patterns/README.md new file mode 100644 index 0000000..0f4f2a6 --- /dev/null +++ b/tutorials/patterns/README.md @@ -0,0 +1,41 @@ +# Common Patterns in Bubble Tea + +So you've started building your app, but now you're not sure if you're doing +things the "right way". + +Well thankfully, we have some common patterns that we see when building Bubble +Tea applications that should help to simplify your decision-making. + +## I only want the model that triggered the message to update + +To figure out whether a component should process the message or not, simply +include an ID in the message. The ID will match the ID field of your child +model and can be handled in that child model's `Update`. + +We use this pattern in our [spinner example](https://github.com/charmbracelet/bubbles/blob/master/spinner/spinner.go) + +These spots in particular: +https://github.com/charmbracelet/bubbles/blob/master/spinner/spinner.go#L145-L149 + +```go + // If an ID is set, and the ID doesn't belong to this spinner, reject + // the message. + if msg.ID > 0 && msg.ID != m.id { + return m, nil + } +``` + +https://github.com/charmbracelet/bubbles/blob/master/spinner/spinner.go#L164 +https://github.com/charmbracelet/bubbles/blob/master/spinner/spinner.go#L195-L203l + +```go +func (m Model) tick(id, tag int) tea.Cmd { + return tea.Tick(m.Spinner.FPS, func(t time.Time) tea.Msg { + return TickMsg{ + Time: t, + ID: id, + tag: tag, + } + }) +} +```