简体   繁体   English

Javascript 库 d3 调用函数

[英]Javascript library d3 call function

I am not able to understand how d3.call() works and when and where to use that.我无法理解 d3.call() 如何工作以及何时何地使用它。 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);

I think the trick here is to understand that xAxis is a function that generates a bunch of SVG elements.我认为这里的技巧是理解 xAxis 是一个生成一堆 SVG 元素的函数。 In fact it is the function returned by d3.svg.axis() .实际上它是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/ ). scale 和 orient 函数只是链接语法的一部分(在此处阅读更多内容: 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).因此svg.append("g")将一个 SVG 组元素附加到 svg 并以选择的形式返回对自身的引用(此处使用相同的链语法)。 When you use call on a selection you are calling the function named xAxis on the elements of the selection g .当您在选择上使用call ,您是在选择g的元素上调用名为xAxis的函数。 In this case you are running the axis function, xAxis , on the newly created and appended group, g .在这种情况下,您将在新创建和附加的组g上运行轴函数xAxis

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"));

What the accepted answer left out IMO is that .call() is a D3 API function and not to be confused with Function.prototype.call() IMO 忽略的公认答案是.call()D3 API 函数,不要与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.唯一的区别是 selection.call总是返回选择,而不是被调用函数name的返回值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM