MVVM — Explained with Examples
Model-View-ViewModel (MVVM) is an architectural pattern that separates UI development from business logic using data binding and commands.
MVVM stands for Model-View-ViewModel. It evolved from MVC and is widely used in frameworks like WPF, Angular, Vue.js, and Knockout.js. The ViewModel acts as a mediator between the Model (data) and the View (UI), exposing data and commands via bindings.
Why MVVM Matters
In traditional UI development, event handlers and UI logic clutter the code-behind, making it hard to test and reuse. MVVM moves all presentation logic into the ViewModel, which is pure code and fully testable. The View becomes a passive projection of the ViewModel state.
Real-World Analogy
Think of a flight departures board at an airport. The Model is the actual flight schedule database. The View is the display screen passengers see. The ViewModel is the processing system that transforms raw schedule data into the formatted, sorted, filtered list shown on the screen. The screen automatically updates when the ViewModel’s data changes.
Example: MVVM with a Counter
// Model — the data
const model = {
count: 0
};
// ViewModel — presentation logic and state
class CounterViewModel {
constructor(initialCount) {
this.count = initialCount;
this.listeners = [];
}
increment() {
this.count++;
this.notify();
}
subscribe(listener) {
this.listeners.push(listener);
}
notify() {
this.listeners.forEach(fn => fn(this.count));
}
}
// View — displays ViewModel state via bindings
const vm = new CounterViewModel(0);
vm.subscribe((count) => {
document.getElementById("display").textContent = count;
});
document.getElementById("btn").addEventListener("click", () => {
vm.increment();
});Expected output: Each click increments the displayed counter without the View directly touching the Model.
Related Terms
MVC, Separation of Concerns, Dependency Injection, Repository Pattern
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro