title: How to create a reusable component in D3 with an API that manipulates each instance of the component?
body: <p>Mike has an excellent article about writing <a href="http://bost.ocks.org/mike/chart/">reusable components</a> in D3. The article describes a pattern of how to make components configurable, and how to apply the component to a selection.</p>
  
  <p>The pattern allows a single component object to be reused with multiple selections by joining it to data; e.g.</p>
  
  <pre><code>var chart = myChart();
  
  d3.select("div.chart")
    .data(data)
    .call(chart);
  </code></pre>
  
  <p>My component implementation looks like the following:</p>
  
  <pre><code>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")
                  .style("fill", "#000")
                  .on("click", toggleState);
  
              function toggleState() {
                  // this function updates the current instance trapped by this closure
                  (state = !state)
                      ? circle.style("fill", "#fff")
                      : circle.style("fill", "#000");
              }
          });
      }
  
      my.toggleState(i) {
          // How do I access the `i`th instance of the component here?
      }
  
      return my;
  }
  </code></pre>
  
  <p>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 <code>div.chart</code> above returns a selection that has two elements, I'd like to call <code>chart.toggleState(1)</code> and have it update the 2nd div in the selection.</p>
  
  <p>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 is 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 to call into a specific instance of a component given its index.</p>