dataBase[0].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(function(d) { return y(d[dataBase[0].columnline]); });
dataBase[1].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(function(d) { return y(d[dataBase[1].columnline]); });
dataBase[2].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(function(d) { return y(d[dataBase[2].columnline]); });
dataBase[3].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(function(d) { return y(d[dataBase[3].columnline]); });
dataBase[4].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(function(d) { return y(d[dataBase[4].columnline]); });
dataBase[5].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(function(d) { return y(d[dataBase[5].columnline]); });
dataBase[6].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(function(d) { return y(d[dataBase[6].columnline]); });
dataBase[7].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(function(d) { return y(d[dataBase[7].columnline]); });
I have tried the statement:
for (var i = 0; i < dataBase.length; i++) {
dataBase[i].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(function(d) { return y(d[dataBase[i].columnline]); });
}
but that did not work because the i in
function(d) {
return y(d[dataBase[i].columnline]);
}
is not the same i as the i in the loop. I have also tried the binding technique from stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
function createfunc(count) {
return function(d) {
return y(d[dataBase[count].columnline]);
};
}
for (var i = 0; i < dataBase.length; i++) {
dataBase[i].valueline = d3.svg.line()
.x(function(d) { return x(d["Date"]); })
.y(createfunc(i));
}
But that also resulted in an error as well. Could someone tell me how to make the eight lines of code into a loop?
As a commenter above said, this is almost certainly a scope issue, but it's difficult to say exactly what kind of scope issue without seeing the surrounding code. One generally good idea if you're having scope issues in JavaScript is to wrap as much as possible in standalone functions, since they each have their own scope and can act as closures to a degree. Maybe try something like:
I have no idea if that will actually work, and even if it does there's probably a better way to build that closure. If you're not familiar with Immediately Invoked Function Expressions, check out this post, and consider finding a way to work them into your code. They are excellent for preventing scope issues in JavaScript.