سؤال

The following jsfiddle works as expected.

However when I add a key function to the data binding it breaks.

 // Use source_target as a key to uniquely identify each link.
 var link = svg.selectAll(".link")
     .data(graph.links, function(d){ return d.source + "_" + d.target; });

After reading the ObjectConstancy tutorial I understood that you could assign a custom key to each element instead of relying on its index for (update, enter, exit).

Is this not the case? What am I doing wrong?

هل كانت مفيدة؟

المحلول

The problem is what d.source and d.target evaluate to as strings -- [object Object]. Remember that the force layout replaces the indices you specify in your data with the corresponding node objects when you run it. You are not seeing all the links you are expecting because of this -- the key function returns the same values for different links, hence they are only added once.

To fix, use e.g. the name of the nodes:

var link = svg.selectAll(".link")
  .data(graph.links, function(d){ return d.source.name + "_" + d.target.name; });

Complete demo here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top