Built with blockbuilder.org
forked from lazingor's block: Update child data when parent data is updated?
license: mit |
Built with blockbuilder.org
forked from lazingor's block: Update child data when parent data is updated?
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
</style> | |
</head> | |
<body> | |
<script> | |
var sampleData = [ [50,50], [100,100] ]; | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", "500px") | |
.attr("height", "400px") | |
.attr("style", "background: #eee"); | |
function update(dataArr) { | |
var groups = svg.selectAll(".group").data(dataArr); | |
var gsEnter = groups.enter().append("g").attr("class", "group"); | |
gsEnter.append("rect") | |
.attr("class", "myrect") | |
.attr("width", "50px") | |
.attr("height", "50px") | |
.attr("fill", "black"); | |
gsEnter.append("circle") | |
.attr("class", "mycirc") | |
.attr("r", "25px") | |
.attr("fill", "blue"); | |
console.warn("a",groups.size()) | |
groups = groups.merge(gsEnter); | |
console.warn("b",groups.size()) | |
groups.selectAll(".myrect") | |
.transition() | |
.attr("x", function(d) { console.warn({d}); return d[0]; }) | |
.attr("y", function(d) { return d[1]; }); | |
groups.select(".mycirc") | |
.transition() | |
.attr("cx", function(d) { console.warn({d}); return d[0]+50; }) | |
.attr("cy", function(d) { return d[1]; }); | |
} | |
update(sampleData); | |
d3.select("body").append("button").text("Update").on("click", newData); | |
function newData() { | |
sampleData = [ [100,200], [150,300], [200,350] ]; | |
update(sampleData); | |
// What happens: the two already created rect+circle pairs stay where they are, and a new one is placed at [200,350] | |
// What I want: the two already created rect+circle pairs to map to the new coordinates, and the new one to be created | |
} | |
</script> | |
</body> |