jQuery → MVC in the browser (Backbone)
2006 – today · 2010 – today
What changed
- Where the state lives
jQuery
In the DOM: a todo is done when its
<li>has the classdone, and the counter is found by counting elements.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
jQuery
The server sends the first HTML. New items are built with
$("<li>")and appended.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
jQuery
Each handler changes the elements it knows about, then
refresh()fixes the counter and the filter.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
jQuery
One script of event handlers. A delegated handler on
#todo-listalso covers items added later.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.
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.
jQuery
jQuery 4.0.0
/src/main.js · 52 lines
// jQuery era: the page itself is the state. Handlers read the DOM, change it, recount.
import $ from "jquery";
// $(fn) waits until the document is ready, like $(document).ready(fn).
$(function () {
let filter = "all";
// Brings the counter, the visible items and the filter buttons in line with the DOM.
function refresh() {
const left = $("#todo-list li").not(".done").length;
$("#todo-count").text(left + " left");
$("#todo-list li").each(function () {
const done = $(this).hasClass("done");
$(this).toggle(filter === "all" || (filter === "done") === done);
});
$("[data-filter]").removeClass("selected");
$('[data-filter="' + filter + '"]').addClass("selected");
}
$("#todo-form").on("submit", function (event) {
event.preventDefault();
const title = String($("#new-todo").val()).trim();
if (!title) return;
// Build the new <li> the same way the server wrote the first ones.
const $item = $("<li>").append(
$("<label>").append(
$('<input type="checkbox" data-toggle>'),
" ",
$('<span class="title">').text(title),
),
);
$("#todo-list").append($item);
$("#new-todo").val("");
refresh();
});
// One delegated handler on the list also covers the items added later.
$("#todo-list").on("change", "[data-toggle]", function () {
$(this).closest("li").toggleClass("done", this.checked);
refresh();
});
$(".filters").on("click", "[data-filter]", function () {
filter = $(this).data("filter");
refresh();
});
refresh();
});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();