liveBook · Manning

DOM update

As explained in Grokking Simplicity

A modification to the Document Object Model that changes a document's represented content, structure, or presentation.

A DOM update changes what the user sees by writing information into the document. Because that write leaves the function without appearing in its return value, it is an implicit output. section 4.8

Treat DOM updates as an action at the edge of business logic:

  • Separate calculations from DOM updates so business rules can be tested without loading a browser, clicking controls, or scraping rendered values. section 4.4
  • Replace direct DOM writes with returned values when the result is synchronous; pass a callback when asynchronous work has not finished. section 4.8 section 15.29
  • Treat the DOM as a shared resource: updates from concurrent timelines can overwrite one another unless a queue puts them into one ordered timeline. section 16.2 section 16.7

Calculating first, updating second

Instead of having calc_cart_total write directly to the page, let it call callback(total). The caller can then choose update_total_dom or send the number to accounting, making the calculation reusable. section 15.29

function calc_cart_total(cart, callback) { #1
    var total = 0;
    cost_ajax(cart, function(cost) {
        total += cost;
        shipping_ajax(cart, function(shipping) {
            total += shipping;
            callback(total); #1
        });
    });
}
 
function add_item_to_cart(name, price, quant) {
    cart = add_item(cart, name, price, quant);
    calc_cart_total(cart, update_total_dom); #2
}

Inspect the callback-based version of cart-total calculation, where the asynchronous result becomes available to either a DOM update or another consumer. section 15.29

How Grokking Simplicity covers it

How deep it goes
Explains implicit outputs, asynchronous callbacks, shared-resource races, and queue ordering, stopping short of browser rendering internals.
Examples
Demonstrates tax display, shopping-cart totals, asynchronous cost and shipping calls, click timelines, and queued updates.
What it assumes
Assumes basic browser interaction, functions, callbacks, asynchronous calls, and global variables while teaching implicit versus explicit inputs and outputs.
What you can do after
Diagnose/debug stale display results by separating calculations, exposing outputs, and serializing competing DOM updates.
How it connects
Connects DOM updates to implicit outputs, explicit outputs, callbacks, asynchronous calls, shared resources, and queues.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.