Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRafael Moreno
17,642 PointsWho passes in "d" in function(d)?
in data.attr('r', function(d)).... I understand that "d" is the data and that you can access certain parts of it with the dot notdation, but who calls the function and passes in "data" as the value for "d"? right now it seems that it just magically happens and that the program knows "d" is "data" without it being explicitly called.
1 Answer
Samuel Webb
25,370 PointsI would suggest reading the D3 API documentation at: https://github.com/mbostock/d3/blob/master/d3.js ... Pay special attention to d3_selectionPrototype.attr
and d3_selection_attr
.
The short answer is that you're just passing in a function that takes an argument, and the function you're creating does something with that argument. You can name the argument whatever you want, but in this instance you're calling it d
. Then that function is passed into the data.attr()
method which calls the passed in function, passing the data into the function using the d
as the variable.
Here's a short example of how something similar works:
function person(name, fn) {
fn(name);
}
person('Sam', function(n){
console.log('Hello ' + n);
});
// This will log:
// Hello Sam
The subject your question is about is Callback Functions. To get a deeper understanding of how they work, here are a few resources you can take a look at:
Rafael Moreno
17,642 PointsRafael Moreno
17,642 PointsThank you!
Samuel Webb
25,370 PointsSamuel Webb
25,370 PointsNo problem. Glad to help.
Sergey Scherbo
5,784 PointsSergey Scherbo
5,784 PointsHello! I think it's easy to understand if u declare your CB function, instead just passing it as a parameter. And it also makes your code easy to read, in my opinion.