Built with blockbuilder.org
Last active
May 14, 2019 21:52
-
-
Save lazingor/77e950c69b5634a0ec39ef92b7fa461c to your computer and use it in GitHub Desktop.
Update child data when parent data is updated?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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"); | |
groups = groups.merge(gsEnter); | |
groups.select(".myrect") | |
.transition() | |
.attr("x", function(d) { return d[0]; }) | |
.attr("y", function(d) { return d[1]; }); | |
groups.select(".mycirc") | |
.transition() | |
.attr("cx", function(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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment