Skip to content
FrontDepth, Home

AJAX → MVC in the browser (Backbone)

1999 – today · 2010 – today

Older era
Newer era
Compare

What changed

Where the state lives

AJAX

On the server: the list is server data; the page keeps the last copy it received, and the filter.

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

AJAX

The server sends data (JSON), not HTML; the page builds the list items with document.createElement.

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

AJAX

Each change is a background request; its callback replaces the page's copy of the list and redraws only the list, the counter and the filter buttons.

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

AJAX

A page script with a request helper and handlers attached in window.onload, talking to a server API that answers JSON.

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. 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.

  2. 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.

AJAX
MVC in the browser (Backbone)

AJAX

plain browser APIs, no library

/src/main.js · 97 lines

JavaScript
// AJAX era: the page talks to the server in the background with XMLHttpRequest and
// redraws only the list. The page itself is never loaded again.

// The list belongs to the server; the page keeps the last copy it received.
var todos = [];
var filter = "all";

// Every request goes the same way: open, send, then wait until readyState is 4 (done).
function request(method, url, body, callback) {
  var xhr = new XMLHttpRequest();
  // true = asynchronous: the page stays usable while the request travels.
  xhr.open(method, url, true);
  if (body) xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      callback(JSON.parse(xhr.responseText));
    }
  };
  xhr.send(body);
}

// Every answer is the whole list as JSON: keep it and redraw.
function show(list) {
  todos = list;
  render();
}

// One call per todo gives each handler its own todo. A handler created inside render()'s
// for loop would close over the loop's single var and see its value from the end of the loop.
function makeItem(todo) {
  var li = document.createElement("li");
  var label = document.createElement("label");
  var box = document.createElement("input");
  var title = document.createElement("span");
  box.type = "checkbox";
  box.checked = todo.done;
  box.setAttribute("data-toggle", "");
  box.onclick = function () {
    request("POST", "/todos/" + todo.id + "/toggle", null, show);
  };
  // A text node: what the user typed never becomes HTML.
  title.className = "title";
  title.appendChild(document.createTextNode(todo.title));
  label.appendChild(box);
  label.appendChild(document.createTextNode(" "));
  label.appendChild(title);
  li.appendChild(label);
  if (todo.done) li.className = "done";
  return li;
}

// Only the list, the counter and the filter buttons change; the rest of the page stays.
function render() {
  var list = document.getElementById("todo-list");
  var buttons = document.getElementById("filters").getElementsByTagName("button");
  var left = 0;
  var i;
  list.innerHTML = "";
  for (i = 0; i < todos.length; i++) {
    if (!todos[i].done) left++;
    if (filter === "all" || (filter === "done") === todos[i].done) {
      list.appendChild(makeItem(todos[i]));
    }
  }
  document.getElementById("todo-count").innerHTML = left + " left";
  for (i = 0; i < buttons.length; i++) {
    buttons[i].className = buttons[i].getAttribute("data-filter") === filter ? "selected" : "";
  }
}

// Handlers are attached from the script when the page has loaded, not written into the HTML.
window.onload = function () {
  var field = document.getElementById("new-todo");
  var buttons = document.getElementById("filters").getElementsByTagName("button");
  var i;

  document.getElementById("todo-form").onsubmit = function () {
    var title = field.value.replace(/^\s+|\s+$/g, "");
    if (title !== "") {
      request("POST", "/todos", "title=" + encodeURIComponent(title), show);
      field.value = "";
    }
    // false cancels the normal submission: no new page, the request runs in the background.
    return false;
  };

  for (i = 0; i < buttons.length; i++) {
    // Inside the handler, this is the button that was clicked.
    buttons[i].onclick = function () {
      filter = this.getAttribute("data-filter");
      render();
    };
  }

  // The page arrives without the list; the first request fetches it.
  request("GET", "/todos", null, show);
};

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();