Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.JS get reference to bound data of clicked object

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!

like image 874
smartexpert Avatar asked Feb 09 '13 08:02

smartexpert


2 Answers

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.

like image 150
Wex Avatar answered Nov 05 '22 19:11

Wex


For the benefit of other newbies out there, this is how I solved this:

//Register the event handler with you selection
myselection.on("click", click);

//Obtain reference to data of currently clicked element by obtaining the first argument of      the event handler function

function click(element){ 
    console.log(element); 
}
like image 29
smartexpert Avatar answered Nov 05 '22 17:11

smartexpert