How to create a reusable component in D3 with an API that manipulates each instance of the component?
===

Mike has an excellent article about writing [reusable components](http://bost.ocks.org/mike/chart/) in D3. The article describes a pattern of how to make components configurable, and how to apply the component to a selection.

The pattern allows a single component object to be reused with multiple selections by joining it to data; e.g.

    var chart = myChart();

    d3.select("div.chart")
      .data(data)
      .call(chart);

The component implementation looks like the following:

    function myChart() {

        function my(selection) {
            selection.each(function(d, i) {

                // generate chart here
                // `d` is the data, `i` is the index, `this` is the element
                
                var state = false;
                
                var circle = d3.select(this).append("circle")
                    .attr("r", "10")
                    .attr("fill", "#000")
                    .on("click", toggleState);
                
                function toggleState() {
                    // this function updates the current instance trapped by this closure
                    (state = !state) ? circle.attr("#000") : circle.attr("#fff");
                }
            });
        }
        
        my.toggleColor(i) {
            // How do I access the `i`th instance of the component here?
        }

        return my;
    }

What I would like to achieve is to allow the caller to manipulate an instance of this component given its index. For example, if the selector `div.chart` above returns a selection that has two elements, I'd like to call myChart.toggleState(1) and have it update the 2nd div in the selection.

Just so I don't confuse anyone why I'm trying to do this, the caller needs to synchronize two types of components together. Imagine I have a component that represented by a circle and another component that is represented by a rectangle. The two components must be independent and not tied to each other. I need to be able to create 4 circles and 4 rectangles, and when I click a rectangle, I'd like to be able to update the corresponding circle based on index order. I have already figured out how to raise events (d3.dispatch) from a component and provide the current index as a parameter in the event, but I haven't figured out how can I call into a specific instance of a component given its index.