D3 class inheritance

38 views
Skip to first unread message

Kevin Etore

unread,
May 19, 2016, 3:55:19 AM5/19/16
to d3-js
He D3.js users, 

I have a question about cutting the D3 to parts such as classes and functions.  I've been trying to do some research if this is possible, but sadly without any succes. 

So let's say the code im using:

















And i want like the SVG in a class method, same with the rectangle. So something like class rectangle < drawingElement(svg)

The above example (the concept) would this be available to do?

Bear in mind that i'm a complete beginner when it comes to D3 :)


Thanks in advance, 

-Kevin

Joe Keohan

unread,
May 19, 2016, 5:40:34 PM5/19/16
to d3-js
Kevin,

Not sure about the classes but you can certainly create modules for encapsulating charts and making them reusable.  A good book to read for t his is "Developing A D3 Edge".  Below is a code snippet on using a reusable bar chart that is defined as d3.edge.barChart = function module() {

var barChart1 = d3.edge.barChart()
    .w(100).h(200)
    .on("customHover", function(d, i) { msg("chart1: " + d); });

var data1 = [10, 20, 30, 40];

d3.select("#container1")
    .datum(data1)
    .call(barChart1);

d3.edge = {};

d3.edge.barChart = function module() {
    var w = 400,
        h = 300;
    var dispatch = d3.dispatch("customHover");
    function exports(_selection) {
        _selection.each(function(_data) {
            var barW = w / _data.length,
                scaling = h / d3.max(_data);
            d3.select(this)
                .append("svg")
                .attr({class: "chart2", width: w, height: h})
                .append("g")
                .selectAll(".bar")
                .data(_data)
                .enter().append("rect")
                .attr({
                    class: "bar",
                    x: function(d, i) { return i * barW; },
                    width: barW,
                    y: function(d, i) { return h - d * scaling; },
                    height: function(d, i) { return d * scaling; }
                })
                .on("mouseover", dispatch.customHover);
        });
    }
    exports.w = function(_x) {
        if (!arguments.length) return w;
        w = _x;
        return this;
    };
    exports.h = function(_x) {
        if (!arguments.length) return h;
        h = _x;
        return this;
    };
    d3.rebind(exports, dispatch, "on");
    return exports;
};


var barChart1 = d3.edge.barChart()
    .w(100).h(200)
    .on("customHover", function(d, i) { msg("chart1: " + d); });

var data1 = [10, 20, 30, 40];

d3.select("#container1")
    .datum(data1)
    .call(barChart1);

Joe

Randy Chung

unread,
May 20, 2016, 11:36:37 AM5/20/16
to d3-js
There was also a post by Mike Bostock about this:

Towards Reusable Charts: https://bost.ocks.org/mike/chart/
Reply all
Reply to author
Forward
0 new messages