Skip to content
FrontDepth, Home

MVC in the browser (Backbone) → Two-way binding (AngularJS)

2010 – today · 2010 – 2021

Older era
Newer era
Compare

What changed

Where the state lives

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

Two-way binding (AngularJS)

On $scope: plain objects in $scope.todos, the filter in $scope.show and the text field's value in $scope.newTitle.

How the page is rendered

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.

Two-way binding (AngularJS)

The HTML is the template: AngularJS compiles the ng-* attributes and {{ }} once, then each binding updates its own piece of the DOM.

What happens on a change

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.

Two-way binding (AngularJS)

Directives run handlers inside $apply; the digest evaluates every watcher again and changes the DOM where a value differs. ng-model also writes from the field back to the scope.

How the code is organised

MVC in the browser (Backbone)

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

Two-way binding (AngularJS)

A module, a controller that fills $scope, and directives in the HTML. The controller has no DOM code.

Why it changed

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

  1. MVC in the browser (Backbone)→Two-way binding (AngularJS)

    Backbone left the wiring to you. Every view subscribed to its models by hand, chose what to redraw and read form fields back itself, so much of the code only connected data to the DOM. A view thrown away without remove() stayed subscribed and kept reacting as a "zombie view", and re-rendering a template replaced elements, losing focus and half-typed text. AngularJS answered with two-way data binding: the HTML declares what shows what, and the framework keeps the page and the data in sync.

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.

MVC in the browser (Backbone)
Two-way binding (AngularJS)

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

Two-way binding (AngularJS)

AngularJS 1.8.3

/index.html · 35 lines

HTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Todos · AngularJS</title>
    <link rel="stylesheet" href="/styles.css" />
  </head>
  <body>
    <!-- The page is the template: ng-* attributes and {{ }} bind it to TodoCtrl's $scope. -->
    <main class="todo-app" ng-controller="TodoCtrl">
      <h1>Todos</h1>
      <!-- A form without an action: AngularJS stops the real submit and calls add(). -->
      <form id="todo-form" ng-submit="add()">
        <!-- Two-way: typing writes $scope.newTitle, and setting newTitle changes the field. -->
        <input id="new-todo" ng-model="newTitle" placeholder="What needs doing?" autocomplete="off" aria-label="New todo" />
        <button id="add" type="submit">Add</button>
      </form>
      <ul id="todo-list">
        <!-- ng-repeat gives every <li> a child scope holding its todo. ng-model="todo.done" writes -->
        <!-- straight into that object, so the controller's list sees the change. -->
        <li ng-repeat="todo in todos | filter:matches" ng-class="{done: todo.done}">
          <label><input type="checkbox" data-toggle ng-model="todo.done" /> <span class="title">{{todo.title}}</span></label>
        </li>
      </ul>
      <div class="footer">
        <span id="todo-count">{{remaining()}} left</span>
        <div class="filters">
          <button type="button" data-filter="all" ng-class="{selected: show == 'all'}" ng-click="show = 'all'">All</button>
          <button type="button" data-filter="active" ng-class="{selected: show == 'active'}" ng-click="show = 'active'">Active</button>
          <button type="button" data-filter="done" ng-class="{selected: show == 'done'}" ng-click="show = 'done'">Done</button>
        </div>
      </div>
    </main>
  </body>
</html>