Иллюстрация привязки данных
by vollossy
HTML
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg style="height: 100, width: 100">
</svg>
<br />
<button id="button">
Добавить круг
</button>
<button id="remove-button">
Удалить круг
</button>
JavaScript
var circles = [];
var svg = d3.select("svg")
function setData(data){
var selection = svg.selectAll("circle").data(data);
selection.enter().append("circle")
.attr("cx", function(d){ return d.x })
.attr("cy", function(d){ return d.y })
.attr("r", 10)
.attr("fill", function(){
return "hsl(" + Math.random() * 360 + ",100%,50%)"
})
selection.exit().remove()
}
var button = document.getElementById("button")
button.addEventListener("click", function(){
circles.push({"x": parseInt(Math.random()*100), "y": parseInt(Math.random()*100)})
setData(circles)
})
var removeButton = document.getElementById("remove-button")
removeButton.addEventListener("click", function(){
circles.pop();
setData(circles);
})