Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  160] [ 2]  / answers: 1 / hits: 19722  / 11 Years ago, thu, june 27, 2013, 12:00:00

Every D3js beginner must be going through this thought, I am pretty much sure about it.



I have been around this thing for few hours now!!!!But I don't know how to use it and what is the difference between them?



function(d){return d}

function(d,i){return d and some more custom code}


for Example--->



var data = [4, 8, 15, 16, 23, 42];



    Function(d):::::

chart.selectAll(div)
.data(data)
.enter().append(div)
.style(width, function(d) { return d * 10 + px; })
.text(function(d) { return d; });

------------------------------------------------------------------------------------

Function(d*i):::::

chart.selectAll(rect)
.data(data)
.enter().append(rect)
.attr(y, function(d, i) { return i * 20; })
.attr(width, x)
.attr(height, 20);

More From » d3.js

 Answers
5

Your example is a good illustrator of the difference between the two.



In the first example, only d is used. d represents the data associated with a given selection. In this case, an array of selected div elements is created, one for each element in the data array:



chart.selectAll(div)
.data(data)
.enter()
.append(div)


This not only creates an array of div elements, but associates data with each of those elements. This is done on a one-to-one basis, with each div corresponding to a single element in the data array. One is associated with '4', one with '8', and so on.



If I then go on to use .text(function(d){...}) on the array of selections, d will refer to the data associated with each selected div, so if I use the following method on my selections:



.text(function(d) { return d; });


Each of my divs will have text added, the value of which is d, or the data associated with the element.



When an array of selections is created, they are also given an index in the array. In your example, this corresponds to the position of their data in the data array. If your function requests both d and i, then i will correspond to this index. Going back to our divs, the div associated with '4' will have an index of '0', '8' will have an index of '1', and so on.



It's also important to note that the character used in the variable requested doesn't matter. The first variable in the function call is always the data, and the second is the index. If i used a method like



.text(function(cat,moose){ return( data is:  + cat +  index is:  + moose)})


cat will correspond to the data of the selection, and moose will correspond to the index.


[#77371] Wednesday, June 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeffn

Total Points: 559
Total Questions: 81
Total Answers: 103

Location: Spain
Member since Thu, Dec 23, 2021
2 Years ago
;