AJAX → jQuery
1999 – today · 2006 – today
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.
jQuery
In the DOM: a todo is done when its
<li>has the classdone, and the counter is found by counting elements.- How the page is rendered
AJAX
The server sends data (JSON), not HTML; the page builds the list items with
document.createElement.jQuery
The server sends the first HTML. New items are built with
$("<li>")and appended.- 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.
jQuery
Each handler changes the elements it knows about, then
refresh()fixes the counter and the filter.- 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.jQuery
One script of event handlers. A delegated handler on
#todo-listalso covers items added later.
Why it changed
What hurt in each era along the way, and the era that came next.
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.
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
plain browser APIs, no library
/src/main.js · 97 lines
// 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);
};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();
});