.call() 函数将函数作为参数而不是结果传递

.call() function passes function as argument instead of result

我在 D3 中看到一些我没有预料到的行为,我不知道如何解决它。使用此代码块:

node.append("text")
    .attr("dy", ".3em")
    .style("text-anchor", "middle")
    .text(function (d) { return d.FSname; })
    .attr("radius", function (d) { return d.r;})
    .call(wrap, function(d) {return d.r;})
   //.call(wrap, 140)
;

这里是 wrap() 函数:

function wrap(text, width) {
    //reflows text to be within a pixel width
    console.log("hit wrap(",text,width,this,")");
    text.each(function () {
        var text = d3.select(this),
            words = text.text().split(/\s+/).reverse(),
            word,
            line = [],
            lineNumber = 0,
            lineHeight = 1.0, // ems
            y = text.attr("y"),
            dy = parseFloat(text.attr("dy")),
            tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
        while (word = words.pop()) {
            line.push(word);
            tspan.text(line.join(" "));
            if (tspan.node().getComputedTextLength() > width) {
                if (line.length > 1) line.pop();
                tspan.text(line.join(" "));
                line = [word];
                tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
            }
        }
    });
}

我想将气泡图的圆半径传递给 wrap 函数,但我在 width 参数中得到的是函数本身,而不是已解析的 d.r。 有没有办法让这个匿名函数在将它传递给 .call() 之前解析为一个值?

.attr("radius", function (d) { return wrap.call(this, d.r) });

如果 wrap returns 一个数字(或一个表示数字的字符串,因为 d3 总是 +value)它会工作正常。

您可以使用 .each() 而不是 .call():

node.append("text")
  ...
  .each(function(d) { wrap(d3.select(this), d.r); });

或者,您可以更改 wrap() 的定义以应用函数:

function wrap(text, widthFunc) {
  // ...
  text.each(function(d) {
    var width = widthFunc(d);
    // ...
  });
}