Dynamic HTML and the browser wars → MVC in the browser (Backbone)
1995 – today · 2010 – today
What changed
- Where the state lives
Dynamic HTML and the browser wars
In the page: a JavaScript array and a filter variable. Nothing is saved; a reload starts again from the code.
MVC in the browser (Backbone)
In models: every todo is a
Backbone.Modelin aCollection, and the filter sits in a model of its own (ui).- How the page is rendered
Dynamic HTML and the browser wars
render()builds the whole list as one HTML string and swaps it in withinnerHTML.MVC in the browser (Backbone)
Each
TodoViewrenders its own<li>from an_.template; the app view updates only the counter and the filter buttons.- What happens on a change
Dynamic HTML and the browser wars
Handler attributes (
onsubmit,onclick) call global functions that change the array and callrender().MVC in the browser (Backbone)
A handler calls
set()on a model; the model fireschange, and every view listening to it re-renders itself.- How the code is organised
Dynamic HTML and the browser wars
One script of global functions, wired to the page by attributes in the HTML. No server is involved.
MVC in the browser (Backbone)
Models, a collection and views connected by events. A view's
eventshash delegates DOM events to its element.
Why it changed
What hurt in each era along the way, and the era that came next.
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.
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 withattachEventinstead ofaddEventListener, 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.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.
Dynamic HTML and the browser wars
plain browser APIs, no library
/src/main.js · 73 lines
// DHTML era: the page changes itself in the browser. The list is a JavaScript array, and
// render() writes it into the page as one HTML string. No server is asked.
// The state is plain variables in the page: a reload starts again from these lines.
var todos = [
{ id: 1, title: "Read the docs", done: true },
{ id: 2, title: "Write the app", done: false }
];
var nextId = 3;
var filter = "all";
var FILTERS = ["all", "active", "done"];
// The text the user typed becomes part of the HTML, so it is escaped first.
function escapeHtml(text) {
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
function render() {
var html = "";
var left = 0;
var i, todo;
for (i = 0; i < todos.length; i++) {
todo = todos[i];
if (!todo.done) left++;
if (filter == "all" || (filter == "done") == todo.done) {
// The handler is part of the string: onclick calls a global function with the id.
html += '<li' + (todo.done ? ' class="done"' : '') + '><label>' +
'<input type="checkbox" data-toggle onclick="toggleTodo(' + todo.id + ')"' +
(todo.done ? ' checked' : '') + '> ' +
'<span class="title">' + escapeHtml(todo.title) + '</span></label></li>';
}
}
// innerHTML throws the old items away and builds new ones, so a focused checkbox loses focus.
document.getElementById("todo-list").innerHTML = html;
document.getElementById("todo-count").innerHTML = left + " left";
for (i = 0; i < FILTERS.length; i++) {
document.getElementById("filter-" + FILTERS[i]).className = FILTERS[i] == filter ? "selected" : "";
}
}
function addTodo() {
var field = document.getElementById("new-todo");
var title = field.value.replace(/^\s+|\s+$/g, "");
if (title != "") {
todos.push({ id: nextId++, title: title, done: false });
field.value = "";
render();
}
// false cancels what the browser would do next: send the form and load a new page.
return false;
}
function toggleTodo(id) {
for (var i = 0; i < todos.length; i++) {
if (todos[i].id == id) todos[i].done = !todos[i].done;
}
render();
}
function setFilter(name) {
filter = name;
render();
}
// A <script> of the time ran in the global scope: every function above became global, and
// the onclick attributes could call it. The lab runs each file as a module with its own
// scope, so the functions the markup calls are put on window by hand.
window.addTodo = addTodo;
window.toggleTodo = toggleTodo;
window.setFilter = setFilter;
// Like a <script> at the end of <body>, this runs when the elements already exist: draw the list.
render();MVC in the browser (Backbone)
Backbone 1.6.1, Underscore 1.13.8, jQuery 4.0.0
/src/main.js · 100 lines
// 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();