Skip to content
Irene Ros edited this page May 23, 2013 · 5 revisions

Charts - extending

Once a chart exists that you want to change or expand the functionality of, the easiest way to do that is using the .extend() method.

.extend(name, protoProps, staticProps)

  • name - the name of the new chart.
  • 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.

Using .extend:

Given the following chart definition:

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

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

d3.chart("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.

The order in which the initialize functions will be called will begin with the first chart (in this case BarChart ) followed by the next chart (CustomBarChart.)

Layer access

An extending 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