Skip to content
FrontDepth, Home

Static HTML and server rendering → MVC in the browser (Backbone)

1991 – today · 2010 – today

Older era
Newer era
Compare

What changed

Where the state lives

Static HTML and server rendering

On the server: the todo list is server data; the current filter is in the URL and in hidden form fields.

MVC in the browser (Backbone)

In models: every todo is a Backbone.Model in a Collection, and the filter sits in a model of its own (ui).

How the page is rendered

Static HTML and server rendering

The server writes the whole page as an HTML string for every request; the browser only displays it.

MVC in the browser (Backbone)

Each TodoView renders its own <li> from an _.template; the app view updates only the counter and the filter buttons.

What happens on a change

Static HTML and server rendering

Every action is a request: a form POST or a link GET, answered by a complete new page.

MVC in the browser (Backbone)

A handler calls set() on a model; the model fires change, and every view listening to it re-renders itself.

How the code is organised

Static HTML and server rendering

One server program that routes requests and renders pages. No JavaScript is needed in the browser.

MVC in the browser (Backbone)

Models, a collection and views connected by events. A view's events hash delegates DOM events to its element.

Why it changed

What hurt in each era along the way, and the era that came next.

  1. Static HTML and server rendering→Dynamic HTML and the browser wars

    Every change, even ticking one checkbox, is a round trip to the server and a new page: the screen flashes, the scroll position and anything half-typed are lost, and the user waits for the network each time. Pages could not react to the user on their own. JavaScript (1995) and Dynamic HTML let the page change itself in the browser.

  2. Dynamic HTML and the browser wars→AJAX

    The page could change itself, but it could not exchange data with the server without leaving: loading fresh data or saving a change still meant a form submission or a link and a whole new page, and everything kept in variables was gone after it. On top of that, every browser needed its own branch of the code. XMLHttpRequest and the AJAX approach let a script talk to the server in the background and update only the part of the page that changed.

  3. AJAX→jQuery

    Every browser did it a little differently. Internet Explorer 5 and 6 created the object with new ActiveXObject("Microsoft.XMLHTTP"), Internet Explorer before version 9 attached events with attachEvent instead of addEventListener, and each browser had its own DOM quirks, so scripts grew long and full of browser checks. Libraries like jQuery wrapped XHR, events and the DOM in one short API that worked the same in every browser.

  4. jQuery→MVC in the browser (Backbone)

    When the data lives only in the DOM, every feature reads and writes the page directly: the counter counts <li> elements, the filter checks classes. As apps grew, handlers changing the page from many places became hard to follow ("jQuery spaghetti"), and there was no model of the data to test, save or reuse. Libraries like Backbone moved the data into models and kept the page in views.

The same app, side by side

The main file of each version. Both apps pass the same test: same markup, same behaviour, different ideas.

The apps run in sandboxes in your browser.

Static HTML and server rendering
MVC in the browser (Backbone)

Static HTML and server rendering

plain browser APIs, no library

/server.js · 83 lines

JavaScript
// Static HTML era: the server builds every page; the browser shows it and sends forms back.
// In the 1990s this was a CGI script (often Perl, later PHP); here it is JavaScript.

// The "database" lives on the server, so the list survives every page load.
const todos = [
  { id: 1, title: "Read the docs", done: true },
  { id: 2, title: "Write the app", done: false },
];
let nextId = 3;

const FILTERS = { all: "All", active: "Active", done: "Done" };

// Text typed by users must be escaped before it goes into the HTML.
function escapeHtml(text) {
  return String(text)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function renderPage(filter) {
  const shown = todos.filter((t) => filter === "all" || (filter === "done") === t.done);
  const left = todos.filter((t) => !t.done).length;

  // Every todo gets its own little form: toggling it is a POST to the server.
  const items = shown
    .map(
      (t) => `
        <li${t.done ? ' class="done"' : ""}>
          <form method="post" action="/todos/${t.id}/toggle">
            <input type="hidden" name="filter" value="${filter}">
            <button type="submit" data-toggle>${t.done ? "Undo" : "Done"}</button>
          </form>
          <span class="title">${escapeHtml(t.title)}</span>
        </li>`,
    )
    .join("");

  // Filters are plain links: choosing one loads a new page.
  const links = Object.entries(FILTERS)
    .map(
      ([name, label]) =>
        `<a href="/?filter=${name}" data-filter="${name}"${name === filter ? ' class="selected"' : ""}>${label}</a>`,
    )
    .join(" ");

  return `
    <main class="todo-app">
      <h1>Todos</h1>
      <form id="todo-form" method="post" action="/todos">
        <input type="hidden" name="filter" value="${filter}">
        <input id="new-todo" name="title" placeholder="What needs doing?" autocomplete="off" aria-label="New todo">
        <button id="add" type="submit">Add</button>
      </form>
      <ul id="todo-list">${items}
      </ul>
      <div class="footer">
        <span id="todo-count">${left} left</span>
        <div class="filters">${links}</div>
      </div>
    </main>`;
}

// One request in, one whole page out. The answer to a POST is the new page itself.
export function handle({ method, path, query, form }) {
  const asked = form?.filter ?? query.filter;
  const filter = Object.hasOwn(FILTERS, asked ?? "") ? asked : "all";

  if (method === "POST" && path === "/todos") {
    const title = (form.title ?? "").trim();
    if (title) todos.push({ id: nextId++, title, done: false });
  }

  const toggle = path.match(/^\/todos\/(\d+)\/toggle$/);
  if (method === "POST" && toggle) {
    const todo = todos.find((t) => t.id === Number(toggle[1]));
    if (todo) todo.done = !todo.done;
  }

  if (path === "/" || method === "POST") return { status: 200, body: renderPage(filter) };
  return { status: 404, body: "<h1>Not found</h1>" };
}

MVC in the browser (Backbone)

Backbone 1.6.1, Underscore 1.13.8, jQuery 4.0.0

/src/main.js · 100 lines

JavaScript
// Backbone era: the data lives in models. Views listen to them and re-render themselves.
import Backbone from "backbone";
import _ from "underscore";
import $ from "jquery";

// A model keeps attributes; set() changes one and fires "change:done", then "change".
const Todo = Backbone.Model.extend({
  defaults: { title: "", done: false },
  toggle: function () {
    this.set("done", !this.get("done"));
  },
});

// A collection is an ordered list of models and passes their events on.
const TodoList = Backbone.Collection.extend({
  model: Todo,
  remaining: function () {
    return this.where({ done: false });
  },
});

const todos = new TodoList([
  { title: "Read the docs", done: true },
  { title: "Write the app", done: false },
]);

// The filter is state too, so it lives in a model that views can listen to.
const ui = new Backbone.Model({ filter: "all" });

// Compiled once into a function. <%- %> escapes the title, <%= %> writes HTML as it is.
const itemTemplate = _.template(
  '<label><input type="checkbox" data-toggle<%= done ? " checked" : "" %>> ' +
    '<span class="title"><%- title %></span></label>',
);

// One view per todo: it owns its <li> and redraws it whenever the model changes.
const TodoView = Backbone.View.extend({
  tagName: "li",
  // Delegated to this.el, so the handler survives every re-render of the <li>.
  events: { "change [data-toggle]": "toggleDone" },
  initialize: function () {
    // listenTo remembers each subscription, so view.remove() can drop them all. A view thrown
    // away without remove() stays subscribed to ui and keeps rendering: a "zombie view".
    this.listenTo(this.model, "change", this.render);
    this.listenTo(ui, "change:filter", this.render);
  },
  render: function () {
    const done = this.model.get("done");
    const filter = ui.get("filter");
    // New HTML replaces the checkbox, so the view has to give keyboard focus back itself.
    const focused = this.el.contains(document.activeElement);
    this.$el.html(itemTemplate(this.model.toJSON()));
    if (focused) this.$("[data-toggle]").trigger("focus");
    this.$el.toggleClass("done", done);
    this.$el.toggle(filter === "all" || (filter === "done") === done);
    return this;
  },
  toggleDone: function () {
    this.model.toggle();
  },
});

// The app view takes over markup that is already in the page: el is a selector.
const AppView = Backbone.View.extend({
  el: ".todo-app",
  events: {
    "submit #todo-form": "create",
    "click [data-filter]": "pickFilter",
  },
  initialize: function () {
    this.listenTo(todos, "add", this.addOne);
    this.listenTo(todos, "add change:done", this.render);
    this.listenTo(ui, "change:filter", this.render);
    todos.each(this.addOne, this);
    this.render();
  },
  addOne: function (todo) {
    this.$("#todo-list").append(new TodoView({ model: todo }).render().el);
  },
  // Renders only what this view owns: the counter and the selected filter.
  render: function () {
    this.$("#todo-count").text(todos.remaining().length + " left");
    this.$("[data-filter]").removeClass("selected");
    this.$('[data-filter="' + ui.get("filter") + '"]').addClass("selected");
    return this;
  },
  create: function (event) {
    event.preventDefault();
    const $input = this.$("#new-todo");
    const title = $input.val().trim();
    if (!title) return;
    todos.add({ title: title });
    $input.val("");
  },
  pickFilter: function (event) {
    ui.set("filter", $(event.currentTarget).data("filter"));
  },
});

new AppView();