---
name: mvvm
description: This skill should be used when the user asks about "mvvm pattern", "model view viewmodel", "when to use mvvm", "data binding", "observable", or mentions needing to synchronize view with data through binding.
version: 1.0.0
---

# MVVM (Model-View-ViewModel) Pattern

## What Is It
MVVM separates the UI (View) from the business logic (Model) using a ViewModel that binds to the View through data binding. Changes in the ViewModel automatically update the View, and user interactions in the View update the ViewModel.

## When to Use
- **WPF/UWP applications** - Native data binding support
- **Knockout.js apps** - JavaScript with observable binding
- **Vue.js applications** - Reactive data binding
- **Complex forms** - Dynamic validation and state management
- **Real-time UI updates** - Data-driven interfaces

## When NOT to Use
- **Simple static UIs** - No need for binding overhead
- **No binding framework** - Manual binding is tedious
- **Performance critical** - Binding adds overhead
- **Server-side rendering** - Use MVC instead

## How to Implement

### Implementation Steps
1. Create Model for data and business logic
2. Create ViewModel with observable properties
3. Implement data binding between View and ViewModel
4. View binds to ViewModel properties and commands
5. ViewModel updates propagate to View automatically

### TypeScript Implementation

```typescript
// Observable property
class Observable<T> {
  private value: T;
  private subscribers: Array<(value: T) => void> = [];

  constructor(initialValue: T) {
    this.value = initialValue;
  }

  get(): T { return this.value; }

  set(newValue: T): void {
    this.value = newValue;
    this.subscribers.forEach(s => s(newValue));
  }

  subscribe(callback: (value: T) => void): void {
    this.subscribers.push(callback);
    callback(this.value); // Initial value
  }
}

// ViewModel
class UserViewModel {
  name = new Observable<string>('');
  email = new Observable<string>('');

  updateUser(name: string, email: string): void {
    this.name.set(name);
    this.email.set(email);
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/mvvm.ts` - Basic implementation with observable binding
- `examples/mvvm-advanced.ts` - Real-world example with form validation

## Related Patterns
- **MVC** - MVVM evolved from MVC
- **MVP** - Similar goals, different binding approach
- **Observer** - Observable properties use Observer pattern
