问题
I am not able to understand how d3.call() works and when and where to use that. Here is the tutorial link that I'm trying to complete.
Can someone please explain specifically what this piece is doing
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
svg.append("g").call(xAxis);
回答1:
I think the trick here is to understand that xAxis is a function that generates a bunch of SVG elements. In fact it is the function returned by d3.svg.axis()
. The scale and orient functions are just part of the chaining syntax (read more of that here: http://alignedleft.com/tutorials/d3/chaining-methods/).
So svg.append("g")
appends an SVG group element to the svg and returns a reference to itself in the form of a selection (same chain syntax at work here). When you use call
on a selection you are calling the function named xAxis
on the elements of the selection g
. In this case you are running the axis function, xAxis
, on the newly created and appended group, g
.
If that still doesn't make sense, the syntax above is equivalent to:
xAxis(svg.append("g"));
or:
d3.svg.axis()
.scale(xScale)
.orient("bottom")(svg.append("g"));
回答2:
What the accepted answer left out IMO is that .call()
is a D3 API function and not to be confused with Function.prototype.call()
selection.call(function[, arguments…])
Invokes the specified function exactly once, passing in this selection along with any optional arguments. Returns this selection. This is equivalent to invoking the function by hand but facilitates method chaining. For example, to set several styles in a reusable function:
Now say:
d3.selectAll("div").call(name, "John", "Snow");
This is roughly equivalent to:
name(d3.selectAll("div"), "John", "Snow");
The only difference is that selection.call always returns the selection and not the return value of the called function, name.
来源:https://stackoverflow.com/questions/12805309/javascript-library-d3-call-function