I have the following javascript code for D3, which behaves strange in my opinion. As I'm new to D3 I might be missing something, but I have no idea at all. The problem is marked by the alert calls:
I loop over a set of data sets which are drawn as lines (stripped from the code) and as circles/dots on these lines. When I click on the circle, I want to execute some code in the onClick handler. The onClick handler is a closer defined per loop iteration which is passed to the D3 on() method. Quite normal javascript stuff so far. But:
The first alert always displays the correct value as I would expect it. I would the value of chartDataItem to be bound to the onClick closure, so it's supposed to have the same value when it's called. But if onClick is executed, I always get the value from the last iteration.
Is there something special with the D3 on() method that I don't see?
for(var i=0; i<chartData.length; i++){
var chartDataItem = chartData[i];
var currentData = chartDataItem["data"];
alert(chartDataItem["name"]); // <- displays the correct value per iteration
var onClick = function(d){
alert(chartDataItem["name"]); // <- should bind chartDataItem to the scope of the closure?!
}
var dataLines = lineChart.dataLinesGroup.selectAll('.data-line color' + i)
.data([currentData]);
// Draw the lines
...
// Draw the points
lineChart.dataCirclesGroup = lineChart.svg.append('svg:g');
var circles = lineChart.dataCirclesGroup.selectAll('.data-point color' + i)
.data(currentData);
circles
.enter()
.append('svg:circle')
.attr('class', 'data-point color' + i)
.style('opacity', 1e-6)
... more attr and style calls ...
.on("click", onClick)
.transition()
.duration(0)
.attr('cx', function(d) { return x(d.title) })
.attr('cy', function(d) { return y(d.value) })
.style('opacity', 1);
...
}