Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a d3 plugin?

Tags:

plugins

d3.js

I would like to make a simple d3 plugin but can't find information on how to do it.

It needs to be very simple:

s.append('text').text("Some Text").editable();

should just translate to

s.append('text').text("Some Text").attr('data-editable', true);

How would I do this?

like image 647
George Mauer Avatar asked Dec 21 '12 03:12

George Mauer


People also ask

Does Grafana use D3?

D3 is already bundled with Grafana, and you can access it by importing the d3 package.

What format does D3 use to create graphics?

D3 uses SVG to create and modify the graphical elements of the visualization. Because SVG has a structured form, D3 can make stylistic and attribute changes to the shapes being drawn.

How do I get D3 JS?

Download D3. js is an open-source library and the source code of the library is freely available on the web at https://d3js.org/ website. Visit the D3. js website and download the latest version of D3. js (d3.

Is d3js open-source?

js, or D3, stands for data-driven documents. It is an open-source JavaScript library that creates interactive data visualizations in a web browser using SVG, HTML, and CSS.


2 Answers

Had to go digging through the source but got it finally.

(function() {
  d3.selection.prototype.editable = function() {
    return this.attr('data-editable', true);
  };
})();

Jsbin here

also note that if you also want the plugin to apply after you .enter() you need to assign the d3.selection.enter.prototype.

If (as in my case) you want your plugin available in both scenarios:

(function() {
    d3.selection.prototype.editable = d3.selection.enter.prototype.editable = function() {
        return this.attr('data-editable', true);
      };
})();
like image 125
George Mauer Avatar answered Oct 20 '22 04:10

George Mauer


Mike Bostock wrote Towards Reusable Charts http://bost.ocks.org/mike/chart/

I followed this pattern to make an extremely simple example d3 plugin, please see this block: http://bl.ocks.org/cpbotha/5073718 (and the source gist: https://gist.github.com/cpbotha/5073718).

According to Mike Bostock, reusable charts should be implemented as "closures with getter-setter methods". I did exactly that in my example above.

The answer of @Wex follows this pattern too, except that it doesn't demonstrate the closure idea, as the original question did not specify requiring any properties.

like image 34
Charl Botha Avatar answered Oct 20 '22 03:10

Charl Botha