liveBook · Manning

Callback

As explained in D3.js in Action, Third Edition

A callback function is a function supplied to another operation so that it can be invoked when a specified event or processing step occurs.

A callback is a function supplied to another operation so it runs at a defined processing step or event. In D3, callbacks can format imported rows or respond to user interaction. section 3.2.2 section 7.2.1

Use callbacks to:

  • Inspect each CSV row as an object and convert values such as counts from strings into numbers. section 3.2.2
  • Return only the key-value pairs needed after the dataset loads, or defer formatting when many columns must be preserved. section 3.2.2
  • React to DOM events through D3's on() method, receiving both the captured event and the selection's attached datum. section 7.2.1

Convert imported rows

d3.csv("../data/data.csv", d => { return { technology: d.technology, count: +d.count }; }); The callback receives one row through d and returns the fields that remain available after loading. section 3.2.2

d3.select("#filters")                                          
  .selectAll(".filter")                                       
  .data(filters)                                              
  .join("button")                                             
    .attr("class", d => `filter ${d.isActive ? "active" : ""}`)
    .text(d => d.label)
    .on("click", (e, d) => {
      console.log("DOM event", e);
      console.log("Attached datum", d);
    });

This callback logs the DOM event and attached datum when a D3-created filter button is clicked. section 7.2.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains row-wise conversion, returned fields, event parameters, and conditional updates without descending into callback execution internals.
Examples
Demonstrates numeric CSV conversion, console logging, filter-button clicks, active-state checks, and histogram updates.
What it assumes
Assumes basic JavaScript functions, objects, and D3 selections while demonstrating callback parameters through concrete data and button examples.
What you can do after
Apply it via D3 to convert imported records and handle events using event and datum parameters.
How it connects
Connects callbacks with D3, CSV, data formatting, event listeners, DOM events, selections, and attached data.

Also explained in

Compare how 19 books explain callback →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.