title: D3: Trouble updating selection
body: <p>I'm having issues with my <code>update()</code> function. Here, within <code>svg.append('rect')</code> I have <code>.on('click')</code> where I simply change the data, then run <code>update()</code>.</p>
  
  <p>Why doesn't this work? How do I make it work?</p>
  
  <pre><code>  var width = 640,
        height = 480;
  
    var graphNodes = [
      { id: 0, x: 39, y: 343, r: 15 },
      { id: 1, x: 425, y: 38, r: 15 },
      { id: 2, x: 183, y: 417, r: 15 },
      { id: 3, x: 564, y: 31, r: 15 },
      { id: 4, x: 553, y: 351, r: 15 },
      { id: 5, x: 454, y: 298, r: 15 },
      { id: 6, x: 493, y: 123, r: 15 },
      { id: 7, x: 471, y: 427, r: 15 },
      { id: 8, x: 142, y: 154, r: 15 }
    ];
  
    var svg = d3.select('body').append('svg')
        .attr('width', width)
        .attr('height', height);
  
    svg.append('rect')
        .attr('class', 'graph')
        .attr('width', width)
        .attr('height', height)
        .attr('fill', 'lightblue')
        .attr('opacity', 0.3)
        .on('click', function(){
  
          graphNodes[8].id = 'hey there'; //  &lt;----- Why doesn't this happen?
  
          update();
        });
  
    var nodeGroup = svg.selectAll('.nodes')
        .data(graphNodes, function(d){ return d.id; })
        .enter().append('g')
        .attr('class', 'node');
  
    nodeGroup.append('circle')
        .attr('cx', function(d) { return d.x })
        .attr('cy', function(d) { return d.y })
        .attr("r", function(d){ return d.r; })
        .attr("fill", "gray");
  
    nodeGroup.append('text')
        .attr("dx", function(d){ return d.x + 20; })
        .attr("dy", function(d){ return d.y + 5; })
        .text(function(d) { return d.id });
  
    function update() {
  
      if(nodeGroup){
  
        // Update nodes
        var node = nodeGroup.data(graphNodes, function(d){ return d.id; }),
            nodeEnter = node.enter().append('g')
                .attr('class', 'node');
  
        nodeEnter.append('circle')
                .attr('cx', function(d) { return d.x; })
                .attr('cy', function(d) { return d.y; })
                .attr('r', function(d){ return d.r; })
                .attr('fill', 'gray');
  
        nodeEnter.append('text')
            .attr("dx", function(d){ return d.x + 20; })
            .attr("dy", function(d){ return d.y + 5; })
            .text(function(d) { return d.id });
  
        nodeGroup = nodeEnter.merge(node);
        node.exit().remove();
      }
    }
  </code></pre>
  
  <p>Here's a <a href="https://jsfiddle.net/g74p0z5v/" rel="nofollow noreferrer">fiddle</a></p>