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
