2

値関数内からデータムの親配列にアクセスする必要があります。より高いレベルにスコープされた変数を使用せずにそれを行う方法はありますか?

言い換えると、

var data = ["a", "b", "c"],
    svg = d3.select("svg");

svg.selectAll("rect").data(data).enter().append("rect")
    .attr("x", function(d, i) {

        // how do I access `d's` parent array from here
        // without using the closure variable `data`?

    });

編集:

私の現実の状況はより複雑であり、このタイプの閉鎖を作成するのは私の場合は厄介なので、私は閉鎖を避けています。

4

2 に答える 2

2

これを行うにはいくつかの方法があります (ただし、閉鎖が最も簡単なオプションだと思います)。

.data()1 つの方法は、現在の選択を呼び出すことです。

var rect = svg.selectAll("rect")
    .data(data);

rect.enter().append("rect")
    .attr("x", function(d, i) {
        console.log(rect.data());
    });

この場合、参照する変数が必要です。これを行うもう 1 つの方法は.call、現在の選択内容を引数として与える を介して実行することです。

svg.selectAll("rect")
    .data(data)
  .enter().append("rect")
    .call(function(selection) {
        // get the data into your scope
        var dataArray = selection.data();
        // do more stuff with the selection
        selection
            .attr("x", function(d, i) {
                console.log(data);
            });
    });
于 2013-05-24T22:44:22.113 に答える
1

You can do the same selection inside the element's attribute method and map each element in the selection to retrive the __data__ attribute:

svg.selectAll('rect')
    .data(data)
    .enter()
    .append("rect")
    .attr('x', function(d, i) {
        // Select the parent, retrive the 'rect' items and get the __data__ of
        // each one
        var parent = d3.select(d3.select(this).node().parentNode),
        items = parent.selectAll('rect')[0],
        parentData = items.map(function(r) { return r.__data__; });
        console.log(parentData);
        return i * 20;
    });

I would rather use the svg variable, but it's possible to do what you want. You can find out more about the attribute __data__ in the docs.

于 2013-05-24T21:33:23.083 に答える