I have data objects that I want to add to SVG. Consider the following pseudo-fragment:
var data = [], counter = 0;
for (var col=1; col<=5; col++)
for (var row=1; row<=3; row++)
data.push({
id: "obj-" + ++counter
,x: col * 120
,y: row * 120
,width: 40
,height: 40
,shape: counter % 2 ? "circle" : "rect"
});
d3.select(".container").selectAll(".obj")
.data(data)
.enter()
.append("g")
.attr("id", function(d){ return d.id; }
Ideally, I would create an object of type Shape, for example.
function Shape(id, shape, x, y, w, h) {
this.id = id;
this.shape = shape;
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.render = function(parent) {
var g = parent.append("g")
.attr("id", this.id);
switch (this.shape) {
case "circle":
g.append("circle")
.attr( )
break;
case "rect":
g.append("rect")
.attr( )
break;
case "triangle":
g.append("polygon")
.attr( )
break;
}
}
}
Then I could do something like:
var data = [], counter = 0;
for (var col=1; col<=5; col++)
for (var row=1; row<=3; row++)
data.push(new Shape({
id: "obj-" + ++counter
,x: col * 120
,y: row * 120
,width: 40
,height: 40
,shape: counter % 2 ? "circle" : "rect"
)});
But how can I call the Shape visualization method from the d3 method? i.e.
d3.select(".container").selectAll(".obj")
.data(data)
.enter()
I'm new to d3, so maybe combining data is the wrong way? Is there any other way to render data items that would be better for this scenario?