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 trial

JavaScript D3.js Styling and Scaling with Data Adding Axes to Your Visualization

Matthew Phelps
Matthew Phelps
190 Points

Callback function question

Around 6:52 when the instructor explains that by using an callback (accessor? anonymous?) function to return "rotate (-65)", this will rotate "each element", instead of "all the elements". To me these two operations sound almost synonymous. Can someone help clarify the difference in relation to how the callback function operates?

1 Answer

In this case, it doesn't matter whether the callback function returns it or not. In fact, it's kind of silly that the function was in there to begin with. I changed that line to

.attr("transform", "rotate(-65)")

with no problem. Normally, we use the callback function to change the return value based on the data. That would look something like this:

.attr("transform", function(d){
           return "rotate(" + (d * 2) + ")";
})

To understand the difference, remember that d3 is traversing through the data you give it one piece at a time. Rotating "all the elements" usually means that all of the elements get rotated by the same amount, and more to the point, there's only one rotation value for all of the elements. This is what we're doing in the workspaces example by setting it to rotate(-65) - every element gets this same value. We wouldn't want to rotate "each element" because this implies that each element would get rotated differently, and in the case of making an x-axis, that would make the text less readable. We do use this for positioning and sizing the dots, like this:

dots.attr('r', 5)
          .attr('cx', function(d) {
            date = parseTime.parse(d.DATE);
            return xScale(date)
          })
          .attr('cy', function(d) {
            return yScale(d.TMAX)
          })
          .style('stroke', '#00ffd2')
          .style('fill', '#006bff');

The attributes 'r', 'cx', and 'cy' are all calculated based on the data that is fed into the function chain. Even if, by some accident of nature or laziness in data collection, they were calculated to be the same, we are still changing "each element" rather than "all elements".

Hope this helps.

Matthew Phelps
Matthew Phelps
190 Points

This is a great explanation and definitely clarifies the situation for me - thanks for taking the time to respond!