title: D3: Using a closure to update a selection without re-binding data
body: <p>I have lifted the following code from <a href="https://bl.ocks.org/mbostock/f705fc55e6f26df29354" rel="nofollow">Mike Bostock's example of using D3 to create a line drawing tool</a>.</p>
  
  <p>This tool creates a drag behaviour that enables the user to draw a curve by dragging on the SVG canvas.</p>
  
  <p>When the drag behaviour starts, the listener for this event captures the coordinates of the start of the behaviour and creates a new SVG path. This listener also attaches a new listener to the event that fires on the continuation of the drag behaviour; this listener (the "drag" listener) updates the SVG path. This occurs on the line of code beginning: <code>active.attr("d", line)</code>.</p>
  
  <p><strong>How does the "drag" listener update the SVG path without an additional line that re-binds the coordinate data (stored in the listener's closure as variable "d") to the SVG path?</strong></p>
  
  <p>By my understanding of how d3 works, this tool shouldn't work. Instead, one would have to change: <code>active.attr("d", line)</code> to <code>active.datum(d).attr("d", line)</code>.</p>
  
  <p>Any help would be much appreciated!</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var line = d3.line()
      .curve(d3.curveBasis);
  
  var svg = d3.select("svg")
      .call(d3.drag()
          .container(function() { return this; })
          .subject(function() { var p = [d3.event.x, d3.event.y]; return [p, p]; })
          .on("start", dragstarted));
  
  function dragstarted() {
    var d = d3.event.subject,
        active = svg.append("path").datum(d),
        x0 = d3.event.x,
        y0 = d3.event.y;
  
    d3.event.on("drag", function() {
      var x1 = d3.event.x,
          y1 = d3.event.y,
          dx = x1 - x0,
          dy = y1 - y0;
  
      if (dx * dx + dy * dy &gt; 100) d.push([x0 = x1, y0 = y1]);
      else d[d.length - 1] = [x1, y1];
      active.attr("d", line);
    });
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt;
  &lt;meta charset="utf-8"&gt;
  &lt;style&gt;
  
  path {
    fill: none;
    stroke: #000;
    stroke-width: 3px;
    stroke-linejoin: round;
    stroke-linecap: round;
  }
  
  &lt;/style&gt;
  &lt;svg width="960" height="500"&gt;
    &lt;rect fill="#fff" width="100%" height="100%"&gt;&lt;/rect&gt;
  &lt;/svg&gt;
  &lt;script src="//d3js.org/d3.v4.min.js"&gt;&lt;/script&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>Update 1:</strong>
  I've experimented with a basic closure structure (i.e. a user-initiated closure which returns a function similar to the "drag" event listener that the user can invoke through the console) but I cannot replicate the way the script works above. I'm completely flummoxed.</p>