I'm building a high-level charting API (on top of d3) as a collection of jQuery plugins.
I'd like to namespace the entire project as 'd3charts', but have each plugin in its own file. So, for example, I might have d3charts.histogram.js and d3charts.pie.js. I want the API to look like this:
<script src="jquery.js"></script>
// I don't really have any common functionality yet, this is an empty file
// not sure if this sort of thing is necessary to achieve the API below
<script src="d3charts.js"></script>
// load only the chart types I want to actually use
<script src="d3charts.histogram.js"></script>
<script src="d3charts.pie.js"></script>
<script>
var foo_data = [ ... ];
var bar_data = [ ... ];
$('.foo').d3charts.histogram(foo_data);
$('.bar').d3charts.pie(bar_data);
</script>
I have individual charts working as regular (non-namespaced) jQuery plugins, see source and pretty display.
What structure do I need in my plugins to make this API work the way I want it to? That means:
// Not this
$('.foo').d3charts().histogram(foo_data);
// Not this either
$.d3charts.pie('.foo', bar_data);
// but chaining should still work:
$('.foo').d3charts.histogram(foo_data).toggleClass('histogramchart');
Other requisite qualities:
- I can't assume any order that the plugins will be loaded.
- Ideally, I'd like a solution where I don't need to load an empty namespace "parent" script like
d3charts.js
. - Inside the original (non-namespaced) plugin, I run my code on every element in the selector using the recommended
return this.each()
. The namespaced plugin should preserve this behavior somehow.
This SO answer seems to be a piece of the puzzle, but I'm not having luck putting the whole picture together.
Thanks for your guidance!