1

Say we have some test data

var testdata1 = [
[
  {x: 1, y: 40},
  {x: 2, y: 43},
  {x: 3, y: 12},
  {x: 4, y: 60},
  {x: 5, y: 63},
  {x: 6, y: 23}
], [
  {x: 1, y: 12},
  {x: 2, y: 5},
  {x: 3, y: 23},
  {x: 4, y: 18},
  {x: 5, y: 73},
  {x: 6, y: 27}
], [
  {x: 1, y: 60},
  {x: 2, y: 49},
  {x: 3, y: 16},
  {x: 4, y: 20},
  {x: 5, y: 92},
  {x: 6, y: 20}
 ] 
];

and we bind the data to some nested objects, like

var circles = svg.select("circle")
    .data(testdata1)
    .enter()
    .append("circle")
var subsel = circles.selectAll("rect")
    .data(function(d) {return d})
    .enter()
    .append("rect")

The third variable in the d3 anonymous function holds the index of the parent data element (as discussed more in Third variable in D3 anonymous function).

Before adding a transition, the j variable behaves as expected (gives 0,1,2 for each group of 6 elements).

After transitioning, however, the j variable becomes undefined:

subsel.attr("foobar", function(d,i,j) {console.log(d,i,j)})
    .transition()
    .attr("foobar", function(d,i,j) {console.log(d,i,j)})   

What's going on?

Community
  • 1
  • 1
Tom Roth
  • 1,954
  • 17
  • 25

1 Answers1

2

The third variable does not becomes undefined after a transition. You can easily check it in this fiddle: https://jsfiddle.net/gerardofurtado/4jahe31t/2/

I changed the console.log to show "before" and "after":

subsel.attr("foobar", function(d,i,j) {console.log("before: 
    x=" + d.x + " y=" + d.y + " i=" + i + " j=" + j)})
.transition()
.attr("foobar", function(d,i,j) {console.log("after: 
    x=" + d.x + " y=" + d.y + " i=" + i + " j=" + j)})

It shows the parent index, as expected:

after: x=1 y=40 i=0 j=0
after: x=2 y=43 i=1 j=0
after: x=3 y=12 i=2 j=0
after: x=4 y=60 i=3 j=0
after: x=5 y=63 i=4 j=0
after: x=6 y=23 i=5 j=0
after: x=1 y=12 i=0 j=1
etc...

I tried to reproduce the behaviour, copying your code verbatim, but I'm still getting the values for j.

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • 2
    Thanks for that. I still kept getting undefined when I tried out your code, but I tried a few things and realised that the version of d3 that I was linking to was an old copy. That was the source of the issue. – Tom Roth Jun 13 '16 at 00:33
  • What was the version? – Gerardo Furtado Jun 13 '16 at 00:43
  • 1
    I was linked to http://mbostock.github.io/d3/d3.js . I'd copied it from some other example a while back. – Tom Roth Jun 13 '16 at 07:11