Update simple example to use new Model interface-based structure

This commit is contained in:
Christian Rocha
2020-10-15 16:08:42 -04:00
parent 26899c73b3
commit 7af3e0e9de

View File

@@ -11,18 +11,9 @@ import (
tea "github.com/charmbracelet/bubbletea"
)
// A model can be more or less any type of data. It holds all the data for a
// program, so often it's a struct. For this simple example, however, all
// we'll need is a simple integer.
type model int
// Messages are events that we respond to in our Update function. This
// particular one indicates that the timer has ticked.
type tickMsg time.Time
func main() {
// Log to a file. Useful in debugging. Not required.
logfilePath := os.Getenv("TEA_LOG")
logfilePath := os.Getenv("BUBBLETEA_LOG")
if logfilePath != "" {
if _, err := tea.LogToFile(logfilePath, "simple"); err != nil {
log.Fatal(err)
@@ -30,23 +21,30 @@ func main() {
}
// Initialize our program
p := tea.NewProgram(initialize, update, view)
p := tea.NewProgram(model(5))
if err := p.Start(); err != nil {
log.Fatal(err)
}
}
func initialize() (tea.Model, tea.Cmd) {
return model(5), tick
// Messages are events that we respond to in our Update function. This
// particular one indicates that the timer has ticked.
type tickMsg time.Time
// A model can be more or less any type of data. It holds all the data for a
// program, so often it's a struct. For this simple example, however, all
// we'll need is a simple integer.
type model int
func (m model) Init() tea.Cmd {
return tick
}
// Update is called when messages are recived. The idea is that you inspect
// the message and update the model (or send back a new one) accordingly. You
// can also return a commmand, which is a function that peforms I/O and
// returns a message.
func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {
m, _ := mdl.(model)
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg.(type) {
case tea.KeyMsg:
return m, tea.Quit
@@ -62,8 +60,7 @@ func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {
// Views take data from the model and return a string which will be rendered
// to the terminal.
func view(mdl tea.Model) string {
m, _ := mdl.(model)
func (m model) View() string {
return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.\n", m)
}