Middle
What is the architectural pattern MVVM?
sobes.tech AI
Answer from AI
The MVVM (Model-View-ViewModel) pattern divides the application into three main parts:
- Model: Represents data and business logic. It is independent of the user interface.
- View: This is the user interface layer. It displays data from the ViewModel and sends user actions to the ViewModel. The View does not contain data processing logic.
- ViewModel: The link between the View and the Model. It provides data from the Model in a format convenient for the View and handles user actions, updating the Model. The ViewModel contains logic for data presentation and user input processing.
Connections between components are usually implemented through data bindings. The View observes changes in the ViewModel and updates automatically, while the ViewModel can respond to events from the View.
// Example of a ViewModel (conditional JavaScript)
class TodoViewModel {
constructor(model) {
this.model = model;
this.todos = this.model.todos; // Provides data for the View
this.newTodoText = ''; // State for the input field in the View
}
addTodo() {
if (this.newTodoText.trim()) {
this.model.addTodo(this.newTodoText.trim());
this.newTodoText = ''; // Clears the field after adding
}
}
removeTodo(index) {
this.model.removeTodo(index);
}
}