Skip to content

Instantly share code, notes, and snippets.

@rettal
Last active August 29, 2015 14:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rettal/7aecc2e6f5b8c10f648b to your computer and use it in GitHub Desktop.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
/*
Code example explaining the enter, update and exit states in D3.
The 3 states basically define the actions that occur when data is added to a selection of elements.
Say if we were selecting data from a database where we had to perform a search with a query string,
each time we ran query the number of rows returned could be more, less, or could be the same but
contain different data, these in essence are the 3 states. more = enter, less = exit, same = update.
The following function illustrates the 3 states by running a function every 3 seconds
that changes (randomly) the data "joined" to the elements in the dom.
The elements in the dom are svg <circle> elements to help illustrate the effect.
*/
setInterval(function() {
var cnt = getRandomInt(3, 10), data = [];
for (var i = 0; i < cnt; i++) {
data.push({"x": Math.random() * (320 - 10) + 10, "y": Math.random() * (320 - 10) + 10});
}
var svg = d3.select("svg");
var circle = svg.selectAll("circle")
.data(data);
circle.exit().remove();
circle.enter().append("circle")
.attr("r", 2.5);
circle
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment