Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8321459
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T23:01:22+00:00 2026-06-08T23:01:22+00:00

I was trying to write a plugin for d3.js recently and have been confused

  • 0

I was trying to write a plugin for d3.js recently and have been confused with something perhaps trivial. There is an explanation on d3’s website on how to go about creating reusable charts. The pattern looks something like this (only the most important details, full code is here):

Design Pattern 1: From d3 website

function timeSeriesChart() {
  var margin = {top: 20, right: 20, bottom: 20, left: 20},
      ...
      area = d3.svg.area().x(X).y1(Y),
      line = d3.svg.line().x(X).y(Y);

  function chart(selection) {
    selection.each(function(data) {

      // Convert data to standard representation greedily;
      // this is needed for nondeterministic accessors.
      data = data.map(function(d, i) {
        return [xValue.call(data, d, i), yValue.call(data, d, i)];
      });

      // Update the x-scale.
      ...

      // Update the y-scale.
      ...

      // Select the svg element, if it exists.
      var svg = d3.select(this).selectAll("svg").data([data]);
      ...

      // Otherwise, create the skeletal chart.
      var gEnter = svg.enter().append("svg").append("g");
      ...    
  }

  // The x-accessor for the path generator; xScale ∘ xValue.
  function X(d) {      }

  // The x-accessor for the path generator; yScale ∘ yValue.
  function Y(d) {      }

  chart.margin = function(_) {
    if (!arguments.length) return margin;
    margin = _;
    return chart;
  };

  chart.width = function(_) {
    if (!arguments.length) return width;
    width = _;
    return chart;
  };

  chart.height = function(_) {
    if (!arguments.length) return height;
    height = _;
    return chart;
  };

  chart.x = function(_) {
    if (!arguments.length) return xValue;
    xValue = _;
    return chart;
  };

  chart.y = function(_) {
    if (!arguments.length) return yValue;
    yValue = _;
    return chart;
  };

  return chart;
}

I have no doubt that this pattern is robust especially because it was suggested by the creator of d3 himself. However, I have been using the following pattern for some time without problems before I came across that post (similar to how plugins are created in general):

Design Pattern 2: General way of creating plugins

(function() {
    var kg = {
        version: '0.1a'
    };

    window.kg = kg;

    kg.chart = {};

    // ==========================================================
    // CHART::SAMPLE CHART TYPE
    // ==========================================================
    kg.chart.samplechart = {

        // ----------------------------------------------------------
        // CONFIGURATION PARAMETERS
        // ----------------------------------------------------------
        WIDTH: 900,
        HEIGHT: 500,
        MARGINS: {
            top: 20,
            right: 20,
            bottom: 20,
            left: 60,
            padding: 40
        },
        xRange: d3.time.scale(),
        yRange: d3.scale.linear(),
        xAxis: d3.svg.axis(),
        yAxis: d3.svg.axis(),
        data: {},

        // ----------------------------------------------------------
        // INIT FUNCTION
        // ----------------------------------------------------------
        init: function() {
            // Initialize and add graph to the given div
            this.update();
        },

        // ----------------------------------------------------------
        // Redraws the graph
        // ----------------------------------------------------------
        update: function() {
            var parentThis = this;
            var newData = parentThis.data;

            // Continue with adding points/lines to the chart


        },
        // ----------------------------------------------------------
        // Gets random data for graph demonstration
        // ----------------------------------------------------------
        getRandomData: function() {
            // Useful for demo purposes  

        }
    };

    // ==========================================================
    // HELPER FUNCTIONS
    // ==========================================================

}());


// EXAMPLE: This renders the chart. 
kg.chart.samplechart.vis = d3.select("#visualization");
kg.chart.samplechart.data = kg.chart.samplechart.getRandomData();
kg.chart.samplechart.init();​    

I have been using Design Pattern 2 for some time without any problems (I agree it is not super clean but I’m working on it). After looking at Design Pattern 1, I just felt it had too much redundancy. For instance, look at the last blocks of code that make the internal variables accessible (chart.margin = function(_) {} etc.).

Perhaps this is good practice but it makes maintenance cumbersome because this has to be repeated for every different chart type (as seen here in a library called NVD3, currently under development) and increases both development effort and risk of bugs.

I would like to know what kind of serious problems I would face if I continue with my pattern or how my pattern can be improved or made closer to spirit of Design Pattern 1. I am trying to avoid changing patterns at this point because that would require a full rewrite and will introduce new bugs into a somewhat stable mini-library. Any suggestions?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T23:01:24+00:00Added an answer on June 8, 2026 at 11:01 pm

    In fact, you can find your second pattern in the d3 source code.

    (function(){
    ...
    d3 = {version: "2.9.6"}; // semver
    ...
    
    d3.svg = {};
    d3.svg.arc = function() {
      var innerRadius = d3_svg_arcInnerRadius,
          outerRadius = d3_svg_arcOuterRadius,
    ...
    

    But the components and generators, like scale, axis, area and layout, tend to use the pattern we can call “charts as closures with getter-setter methods” or ” higher-order programming
    through configurable functions”. You can follow this discussion on the Google Group thread for rationale.

    Personally, I don’t like this redundancy neither, even if it is useful and fairly readable. So I generate these getters and setters automatically using a custom function:

    d3.helper.createAccessors = function(visExport) {
        for (var n in visExport.opts) {
            if (!visExport.opts.hasOwnProperty(n)) continue;
            visExport[n] = (function(n) {
                return function(v) {
                    return arguments.length ? (visExport.opts[n] = v, this) : visExport.opts[n];
                }
            })(n);
        }
    };
    

    Which I use like this at the end of my chart module:

    d3.helper.createAccessors(chart, opts);
    

    Where opts is the name of all the public function:

    var opts = {
                width: 200,
                margin: [5, 0, 20, 0],
                height: 200,
                showPoints: true,
                showAreas: false,
                enableTooltips: true,
                dotSize: 4
            };
    

    Here is a complete example: http://jsfiddle.net/christopheviau/YPAYz/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been trying to write a Controller Plugin which I will be using
I'm trying to write a jquery plugin and i have a question about the
I'm trying to write a new plugin since I haven't been able to find
So I'm trying to write a new plugin since I haven't been able to
I'm trying to write username validation using jquery, I'm using jmsajax plugin.I have tested
I am trying to write a jQuery plugin that will have similar functionality to
I'm trying to write a plugin system to provide some extensibility to an application
I'm trying to write a plugin that aliases some methods in ActiveRecord in the
I'm trying to write a plugin that will extend InheritedResources . Specifically I want
I'm trying to write a jQuery plugin to prevent users from typing numbers with

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.