Привязка данных с обновлением

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');
var circle = svg.selectAll("circle") // 1
  .data(circles) // 2
    .style("fill", "blue"); // 3

circle.exit().remove(); // 4

circle.enter().append("circle") // 5
    .style("fill", "green") // 6
  .merge(circle) // 7
    .style("stroke", "black"); // 8
    
function setData(data){
  circle.datum(data);
}
    
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);
})