This question is a variation. How to create data-based items? or how to add items dynamically? template. In my opinion, your approach will be too complicated and cluttered, because you need to duplicate functions to create elements in your data. This does not seem like an elegant solution.
, .. {type: "circle"}, {type: "rect"} .., selection.append() . , , , , , :
# . () <>
[...]
, , (d), (i) (), DOM, .
:
d3.selectAll('g.legend')
.data([
{ type: 'rect', other: info },
{ type: 'circle', other: info }
])
.enter().append('g')
.append(function(d) {
return document.createElementNS(d3.namespaces.svg, d.type);
});
user2167582 .
D3 v4 d3-selection-multi , , - . , :
var elementsAndAttributes = [
{ type: 'rect', attrs: { "fill": "blue", "width": "10", "height": "10" } },
{ type: 'circle', attrs: { "fill": "red", "cx": "20", "cy": "20", "r": "10" } }
];
:
d3.selectAll('g.legend')
.data(elementsAndAttributes)
.enter().append('g')
.append(function(d) {
return document.createElementNS(d3.namespaces.svg, d.type);
})
.attrs(function(d) {
return d.attrs;
});
D3 v3 -. v3 , (. № 277 " "), , . ). selection.each() .
d3.selectAll('g.legend')
.data(elementsAndAttributes)
.enter().append('g')
.append(function(d) {
return document.createElementNS(d3.ns.prefix.svg, d.type);
})
.each(function(d) {
d3.select(this).attr(d.attrs);
});
, D3 , , selection.each(), D3 v3, v4.
: "- d3".