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

时间:2015-11-10 16:56:01

标签: javascript d3.js bubble-chart

我在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()之前解析为某个值?

2 个答案:

答案 0 :(得分:2)

您可以使用.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);
    // ...
  });
}

答案 1 :(得分:0)

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

如果wrap返回一个数字(或代表数字的字符串,因为d3总是+值),它将正常工作。

相关问题