Skip to content
Irene Ros edited this page Feb 19, 2014 · 5 revisions

Charts - extending

Once a chart constructor exists, one may want to change or expand its capability without destroying the original constructor functionality. The easiest way to do so is by using the .extend() method that is available on all chart constructors once they are defined.

The extend method takes the following arguments:

  • name - the name of the new chart constructor
  • protoProps - the functions/properties that go on the prototype of the chart (available to each instance)
  • staticProps - the functions/properties that go on the chart constructor itself.

For example, given a chart we've defined like so:

d3.chart("BarChart", {
  initialize: function() {
    //...
  },
  //... 
});

One could extend it to create a customized version like so:

d3.chart("BarChart").extend("CustomBarChart", {
  initialize : function() {
    //...
  },
  //...
});

When creating an instance of CustomBarChart, all the properties/functions defined on the original BarChart will be available, as well as those defined on the CustomBarChart.

Both initialize functions will be called, beginning with the first chart (in this case BarChart) followed by the next chart (CustomBarChart.)

Note that besides the initialize & transform methods as well as the dataAttrs property, when defining a method on an extended chart that has the same name as a method in the original chart, that method will be overwritten.

Layer access

An extended chart has access to its parent's layers and can attach to their lifecycle events.

For example, given a CircleChart that has a circles layer that renders red circles, one can create an extension chart that will render those in blue. See the original chart in the why lifecycle events guide.

// define an extended chart from the CircleChart:
d3.chart("CircleChart").extend("BlueCircleChart", {
  initialize: function() {

    // on the circles layer, hook into the enter lifecycle event
    this.layer("circles").on("enter", function() {

      // alter the style of the selection (in this case the circles)
      // and set their fill to be blue instead.
      return this.style("fill", "blue");
    });
  }
});

var data = [10,30,40,50,70,80,120];
var chart = d3.select("#test")
  .append("svg")
  .style("width", 200)
  .style("height", 200)
  .chart("BlueCircleChart");

chart.draw(data);
Clone this wiki locally