We want to make sure that our visualization can react to changing data, with minimal effort from the program that calls our code. One way to test different permutations of data and ensure that the visualization reacts accordingly is to randomly create example data, call the visualization code a number of times, and witness the result. These operations are handled in the factories directory. Let's take a look at the viz_factory.js file as an example:
(function() {
var viz = d3.charts.viz();
Create a variable to store our function with getters and setters as closures. In this example, we will use an anonymous function as a wrapper to execute the code. This prevents conflicts with other JavaScript code and ensures that our visualization will work properly in a protected context:
var rand = function() {
return Math.floor((Math.random() * 10) + 1)
};
A simple helper function that generates a random number between 1 and 10 is as follows:
var data = function() {
return [1,2,3].map(function(d,i) {
var cost = rand();
var sales = rand();
return {
category: 'category-'+i,
cost: cost,
sales: cost + sales
};
});
};
Generate a fake dataset based on random numbers:
d3.select("#chart").datum(data()).call(viz.draw);
Draw the visualization for the first time using these lines of code:
var id = setInterval(function() {
var d = data();
console.log('data:', d);
d3.select("#chart").datum(d).call(viz.draw);
}, 2000);
setTimeout(function() {
clearInterval(id);
}, 10000);
Set a timer for 10 seconds and bind new data to the visualization on iteration. The expected behavior is that the visualization will redraw itself on each call. Notice how simple it is to pass new data to the visualization. It is a simple selector with a new dataset. We have constructed the reusable visualization code in such a way that it knows how to react appropriately.
To see the results in action, simply launch http-server, as follows:
node_modules/http-server/bin/http-server
Now, visit http://localhost:8080.