D3 Data Binding - When to Put Brackets Around Data

I am looking at a few D3 code examples similar to this:

var data = [1,2,3...]; var blah = d3.selectAll("#blah").data([data]).enter()...; 

But sometimes I see it as:

 var data = [1,2,3...]; var blah = d3.selectAll("#blah").data(data).enter()... 

All the code I wrote was in the second form, and I never had a problem, but I copied an example of code on the Internet that was in the first form, and this did not work when I deleted [].

Can someone explain why this is necessary here, and when should we put brackets around what is already an array object?

Thanks.

+5
source share
1 answer

In d3. The data() method takes three things:

  • Function
  • Array
  • Nothing (when he acts as a recipient).

However, this is a problem:

In most situations, you can simply pass ["foo", "bar", "baz"] as data. So, if you have:

 var data = ["foo", "bar", "baz"]; 

You can simply write:

 .data(data) 

However, in some situations, when an element inherits the data of the parent group, you must wrap it in an additional pair of brackets (check this last answer I wrote). We do this because the child gets its data as a function where the parent data is passed.

Check this:

 var data = ["foo", "bar", "baz"]; var body = d3.select("body"); var divs = body.selectAll(".divs") .data(data) .enter() .append("div"); var par = divs.selectAll("p") .data(d => d) .enter() .append("p") .text(d => d); 
 <script src="https://d3js.org/d3.v4.min.js"></script> 

Now the same code with an extra pair of brackets:

 var data = ["foo", "bar", "baz"]; var body = d3.select("body"); var divs = body.selectAll(".divs") .data([data]) .enter() .append("div"); var par = divs.selectAll("p") .data(d => d) .enter() .append("p") .text(d => d); 
 <script src="https://d3js.org/d3.v4.min.js"></script> 

In the first fragment 3 divs are created. For each of them, a string fact is passed in the paragraphs (d3 turns each line, for example, "foo" , into an array, such as ["f", "o", "o"] , and you get 3 paragraphs for each div).

In the second fragment, only one div is created (since the length of our array is 1), and the entire internal array ( ["foo", "bar", "baz"] ) is transferred to paragraphs.

+6
source

Source: https://habr.com/ru/post/1261816/


All Articles