MVC / MVVM — Design Patterns

MVC and MVVM split a page into the Model (data and rules, model.find, model.estimate), the View (what the user sees), and the part linking them. In MVC, the…

The first page you write usually puts everything in one event listener: read the input, find the data, work out the estimate, then write to the DOM. It works, until a second page needs the same estimate, or the data changes on the server.

MVC and MVVM are two ways to split a page's code into three parts, each with its own job: the Model (the data and its business rules), the View (what the user sees), and a third part linking them: the Controller in MVC, the ViewModel in MVVM. Picture a restaurant. The kitchen keeps the ingredients and recipes (the Model), the dining table is what guests see (the View), and the waiter takes the order, passes it to the kitchen, then brings the right plate to the table (the Controller). MVVM swaps the waiter running back and forth for a connected order board: what a guest writes shows up in the kitchen at once, and what the kitchen changes shows up at the table at once.

The problem: everything mixed into one event listener

The first tracking page puts everything in the button's handler:

document.querySelector("#track").addEventListener("click", () => {
  const trackingNo = document.querySelector("#tracking-no").value.trim()
  const parcel = PARCELS[trackingNo]
  document.querySelector("#status").textContent = parcel ? trackingNo + ": " + parcel.status : trackingNo + " not found"
  document.querySelector("#service").textContent = parcel ? parcel.service + ", ETA " + ETA[parcel.service] : ""
})

The arrival-estimate rule hides in a click handler, so the mobile app has to copy it. That rule can't be tested without a browser. And when a parcel's status changes on the server, nothing updates the page, because the display code only runs when the button is clicked.

The Model: the data and its rules

Both versions use the same Model. The Model doesn't know there's a page:

const $ = (selector) => document.querySelector(selector)
const ETA = { regular: "3 days", express: "1 day", cargo: "5 days" }

const model = {
  parcels: {
    "KCL-0001": { status: "transit", service: "regular" },
    "KCL-0002": { status: "delivering", service: "express" },
  },
  listeners: [],
  find(trackingNo) { return this.parcels[trackingNo] ?? null },
  estimate(parcel) { return parcel.status === "delivered" ? "arrived" : ETA[parcel.service] },
  changeStatus(trackingNo, status) {
    this.parcels[trackingNo].status = status
    this.listeners.forEach((fn) => fn(trackingNo)) // tell whoever listens
  },
  onChange(fn) { this.listeners.push(fn) },
}

MVC: the Controller takes input and picks the View

// View: only displays, doesn't know where the data comes from
const view = {
  show(trackingNo, parcel, estimate) {
    $("#status").textContent = trackingNo + ": " + parcel.status
    $("#service").textContent = parcel.service + ", ETA " + estimate
  },
  notFound(trackingNo) {
    $("#status").textContent = trackingNo + " not found"
    $("#service").textContent = ""
  },
}

// Controller: takes input, asks the Model, picks the display
const controller = {
  active: null, // the tracking number on display
  track() {
    this.active = $("#tracking-no").value.trim()
    this.show()
  },
  show() {
    const parcel = model.find(this.active)
    if (parcel) view.show(this.active, parcel, model.estimate(parcel))
    else view.notFound(this.active)
  },
}

$("#track").addEventListener("click", () => controller.track())
model.onChange((trackingNo) => { if (trackingNo === controller.active) controller.show() })

You'll meet MVC most often on the server: in Laravel, a route calls a controller, the controller asks an Eloquent Model, then return view("tracking", ["parcel" => $parcel]) picks a Blade View. Express writes it res.render("tracking", { parcel }).

⚠️ The original MVC, in Smalltalk-80, is a little different. There the View observes the Model through Observer and redraws itself when the Model changes, while the Controller only changes the Model. The version above, with a Controller that picks the View, is the web and server variant. There is also MVP (Model-View-Presenter): the View is passive, and the Presenter fills it through methods such as view.showStatus(...). So the Presenter can be tested with a fake View.

MVVM: the ViewModel and binding

MVVM keeps the page's state in the ViewModel as values that can be listened to (observables), and binding connects them to the DOM. An observable is lesson 3's Observer, for a single value:

function observable(value) {
  const subs = []
  return {
    get: () => value,
    set(v) {
      if (v === value) return // the same: nobody needs telling
      value = v
      subs.forEach((fn) => fn(v))
    },
    subscribe(fn) { subs.push(fn); fn(value) },
  }
}

// ViewModel: the page's state, never touches the DOM
const vm = {
  trackingNo: observable(""),
  status: observable(""),
  service: observable(""),
  active: null,
  track() { vm.active = vm.trackingNo.get().trim(); vm.load() },
  load() {
    const parcel = model.find(vm.active)
    vm.status.set(parcel ? vm.active + ": " + parcel.status : vm.active + " not found")
    vm.service.set(parcel ? parcel.service + ", ETA " + model.estimate(parcel) : "")
  },
}
model.onChange((trackingNo) => { if (trackingNo === vm.active) vm.load() })

// Binding: the only part that touches the DOM
function bindText(selector, obs) {
  obs.subscribe((v) => { $(selector).textContent = v })
}
function bindInput(selector, obs) {
  obs.subscribe((v) => { if ($(selector).value !== v) $(selector).value = v }) // ViewModel to View
  $(selector).addEventListener("input", (e) => obs.set(e.target.value))         // View to ViewModel
}
bindInput("#tracking-no", vm.trackingNo)
bindText("#status", vm.status)
bindText("#service", vm.service)
$("#track").addEventListener("click", () => vm.track())

The ViewModel only changes values. Binding writes to the DOM, and only for values that changed. When the server changes KCL-0001 to delivering, MVC rewrites #status and #service (2 elements), while MVVM only writes #status (1 element), because service is still regular, ETA 3 days.

Two-way binding

Before going on, take a guess: the code runs vm.trackingNo.set("KCL-0002"), and the ViewModel vm has not a single line that touches the DOM. What happens to the tracking-number input box on the page?

bindInput connects both ways. From View to ViewModel: each keystroke fires an input event, and vm.trackingNo takes the text. From ViewModel to View: each vm.trackingNo.set(...) writes the input box. So vm.trackingNo.set("KCL-0002") makes the input box read KCL-0002, even though the ViewModel never touches the DOM. In MVC, the Controller has to write $("#tracking-no").value = "KCL-0002" itself.

That's MVVM's edge on the frontend: two-way binding between ViewModel and View cuts down the DOM-manipulation code written by hand. Vue does it with v-model, Angular with [(ngModel)]. React binds one way (state to display), so input changes come back through an onChange you write yourself. As a bonus, a ViewModel can be tested without a browser: vm.trackingNo.set("KCL-0001"), vm.track(), then vm.status.get() holds KCL-0001: transit.

When to use which

⚠️ Signs the parts are getting mixed up again

TL;DR: MVC and MVVM split a page into the Model (data and rules, model.find, model.estimate), the View (what the user sees), and the part linking them. In MVC, the Controller takes input, processes it, and decides which View to show (show or notFound), like a Laravel controller that does return view(...). In MVVM, the ViewModel keeps state as observables without touching the DOM, and binding writes to the DOM, only for values that changed (a server update: MVC 2 elements, MVVM 1). Two-way binding (v-model in Vue) makes vm.trackingNo.set("KCL-0002") fill the input box and the user's typing fill vm.trackingNo, so there's less DOM-manipulation code. For a one-button page, one function is enough.

⚡ Three parts, three jobs

Meaning: MVC and MVVM split a page's code into the Model (the data and its business rules, unaware of any page), the View (what the user sees), and a part linking them. An estimate rule hidden in a click handler has to be copied into every display, and can't be tested without a browser.

⚡ MVC: the Controller picks the View

Write:

const controller = {
  active: null, // the tracking number on display
  track() {
    this.active = $("#tracking-no").value.trim()
    this.show()
  },
  show() {
    const parcel = model.find(this.active)
    if (parcel) view.show(this.active, parcel, model.estimate(parcel))
    else view.notFound(this.active)
  },
}

Meaning: The Controller takes the user's input, asks the Model, then decides which View to show. The View only writes to the DOM from the data it's given.

⚡ MVVM: two-way binding

Write:

bindInput("#tracking-no", vm.trackingNo)
Guess first: the code runs vm.trackingNo.set("KCL-0002"), and the ViewModel has not a single line that touches the DOM. What happens to the tracking-number input box?

The input box reads KCL-0002. bindInput connects both ways: the user's typing fills vm.trackingNo, and vm.trackingNo.set(...) writes the input box.

Meaning: Two-way binding between ViewModel and View cuts down the DOM-manipulation code written by hand, like v-model in Vue. A small one-button page needs only one function.

What you will learn