(9) Using the D3 library within a custom widget

Overview

D3.js is a great JavaScript library for various visualizations. It provides strong tools for creating any kind of visualization, be it a chart or a widget. MashZoneNG internally uses D3 for its charting library and widgets, e.g. Slider or Date Filter.

In MashZone version 10.2 and earlier D3 version 3.3.13 was used (this version will be referred to as D3V3). In MashZone version 10.3 the used D3 library was updated to version 5.0.0 (this version will be referred to as D3V5). As existing custom widgets might use the D3V3 library still, MashZone now supports both versions D3V3 and D3V5 in parallel.

Exposing the API

As the D3 library uses the global variable "window.d3" to make itself available for usage, both the versions are trying to assign themselves to "window.d3". In order to run both D3 versions in parallel, the following adjustments where done:

  • The D3V3 library was not modified and still uses the global variable window.d3 to make itself available
  • The D3V5 library is assigning itself to the global variable window.d3v5 instead of window.d3
  • An API was exposed to fetch the required D3 version from the available D3 libraries
MZNG.Viz
MZNG.Viz = {
    getD3Instance: function(latest, versionSuffix) {
        if(latest) {
            // if the requested version is unavailable, then we fall back to whatever version of d3 is available by default
            return window["d3" + (versionSuffix || "v5")] || window.d3;
        }
        return window.d3;
    }
};

Using the API

MZNG.Viz.getD3Instance is now available in the custom widget framework and can be used as follows:

 

MZNG.Viz usage
// returns what ever is assigned to window.d3 variable
var d3v3 = MZNG.Viz.getD3Instance(false);
 
// returns the latest D3 library, currently window.d3v5 as versionSuffix defaults to 'v5' is not provided
var d3Latest = MZNG.Viz.getD3Instance(true);
 
// returns the latest D3 library, currently window.d3v5
var d3v5 = MZNG.Viz.getD3Instance(true'v5');
 
// returns the default D3 library assigned to window.d3 variable as unavailable versionSuffix has been provided
var d3Default = MZNG.Viz.getD3Instance(true'v4');

Recommendations

In case a custom widgets runs with D3V3, no code update is necessary.

In case a custom widgets is supposed to run with D3V5 please use d3 as a local variable to hold the latest D3V5 library. Example: d3.selectAll("rect") 

Notes

D3V3 will most probably be removed in future versions of MashZone NG. Updating custom widgets to D3V5 is recommended.

Read in this series: