D3.JS get reference to bound data of clicked object

smartexpert picture smartexpert · Feb 9, 2013 · Viewed 13k times · Source

I am a newbie to javascript and D3.js

I am working with the Force Directed Graph Example at https://gist.github.com/4062045

I need to get a reference to the bound data of the clicked circle element so that I can add a link to it.

I have the following line of code in the circle's click handler:

d3.select(this).each(function(d){console.log(d)});

I am able to print the object to console but I can't figure out how to get a reference to this object so that I can push it into a link object like:

{source: <reference to node should go here>, target: some_other_node}

Appreciate your help guys!

Answer

Wex picture Wex · Feb 9, 2013
circles.on('click', datum => {
  console.log(datum); // the datum for the clicked circle
});

# selection.on(typenames[, listener[, capture]])

When a specified event is dispatched on a selected node, the specified listener will be evaluated for each selected element, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element.