Event handler in Collapsable Tree leaf

I am using Mike Bostock’s Tidy Tree to show hierarchies: Collapsible tree / D3 | Observable

I am trying to add an event handler to the leaves so that when a leaf is clicked, it triggers another process defined in a separate code cell within my notebook.

When I modify this event handling code in Mike’s code:

.on("click", (event, d) => {
          d.children = d.children ? null : d._children;
          update(event, d);
        });

with this:

.on("click", (event, d) => {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(event, d);
});

the expand/collapse of the leaves breaks. I’m not sure why this is happening. Is it specific to this code or is there a more general Observable/D3 protocol that I’m running into?

Here’s a modified version with the second snippet:

1 Like

I only see the original handler code in your notebook, but even if I change it to your modified example both expanding and collapsing continue to work for me.