title: How can I make D3 events working on dynamic elements in a bar chart?
body: <p>Here is what I'm trying to do: I have an array of objects, with several interesting properties. What I'm trying to do is to build an application where the user can select the name of one property and the related data are displayed in a bar chart. Than the user should be able to click on a specific bar, that should change its color.</p>
  
  <p>So basically I have this function </p>
  
  <pre><code>function updateBarChart(propertyName)
  </code></pre>
  
  <p>This is the summarised content of this function:</p>
  
  <p>It binds the rects of the bar chart to my data (data is always the same):</p>
  
  <pre><code>const bars = d3.select("#barchart")
      .selectAll("rect")
      .data(data);
  </code></pre>
  
  <p>The new rectangles are styled properly:</p>
  
  <pre><code>const bars2 = bars.enter()
      .append('rect')
      .attr(attrs);
  </code></pre>
  
  <p>The bars2 constant in my opinion should not be necessary but as you will see, it is.</p>
  
  <p>The current bars are styled properly:</p>
  
  <pre><code>bars.attr(attrs)
  </code></pre>
  
  <p>Old bars are removed:</p>
  
  <pre><code>bars.exit().remove();
  </code></pre>
  
  <p>Now the event handling part, the one that in my mind should work, here I comment the lines not working as I would expect:</p>
  
  <pre><code>bars.on('click', function() { //1
      console.log(propertyName); //2
      bars.attr('fill', oldColor); //3
      d3.select(this).attr('fill', differentColor);
  }
  </code></pre>
  
  <p>Now the problems:</p>
  
  <p>//1 => Here bars doesn't work, if I use bars2 instead it works. Why is that?</p>
  
  <p>//2 => Here propertyName does not change when the user changes the select property. Should the click event handler be unregistered and registered again when the user changes the selected property? How can I do it? Why is that?</p>
  
  <p>//3 => Here if I use bars like in the example it doesn't work. What I need to do is subsitute bar with d3.select("#barchart").selectAll('rect'). Again, why is that?</p>
  
  <p>I'm not really sure I understand how d3 works, so I'm sorry if the question seems a little bit like a "teach me d3 for free!".</p>