update.rs
Finally we have the update.rs
file. Here, the update()
function takes in two arguments:
key_event
: This is an event provided by thecrossterm
crate, representing a key press from the user.app
: A mutable reference to our application’s state, represented by theApp
struct.
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::app::App;
pub fn update(app: &mut App, key_event: KeyEvent) {
match key_event.code {
KeyCode::Esc | KeyCode::Char('q') => app.quit(),
KeyCode::Char('c') | KeyCode::Char('C') => {
if key_event.modifiers == KeyModifiers::CONTROL {
app.quit()
}
},
KeyCode::Right | KeyCode::Char('j') => app.increment_counter(),
KeyCode::Left | KeyCode::Char('k') => app.decrement_counter(),
_ => {},
};
}
Note that here we don’t have to check that key_event.kind
is KeyEventKind::Press
because we
already do that check in event.rs and only send KeyEventKind::Press
events on the
channel.
As an exercise, can you refactor this app to use “The Elm Architecture” principles?
Check out the concepts page on The Elm Architecture for reference.