title: How to associate javascript code with dom elements?
body: <p>I have various dom elements that have their contents updated at page load time. Typically they are updated by ajax with data from the server. They usually show things like charts and tabular information.</p>
  
  <p>To keep things clean, I have reused the code that generates the final html for common tasks such as displaying a chart. I put options in the html attributes and have an attribute for the data url. e.g.</p>
  
  <pre><code>&lt;div class="standard_chart"
       chart_title="Trend of X vs. Y"
       data_url="/data/x_vs_y"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>This organisation has significantly improved my js code.</p>
  
  <p><strong>The Problem</strong></p>
  
  <p>Sometimes I need to process the data first. For example, to filter it:</p>
  
  <pre><code>var filter_outliers_for_x_vs_y_data = function(data){
      data = data.filter(function(d){
          return -1000 &lt; d.y &amp;&amp; d.y &lt; 1000;
      });
      return data;
  };
  </code></pre>
  
  <p>I am loath to put an id attribute on the div just to re-write the data processing function for that particular dom id. Consider this:</p>
  
  <pre><code>$(document).ready(function(){
      $('#my_x_vs_y_chart').each(function(){
           // ... reworked code just for this element
      });
  });
  </code></pre>
  
  <p>I'd much rather, in that html document, put the pre-processing function right next to the html element (or in it). That seems like the best place for it.</p>
  
  <p>What would be the best way to associate javascript with particular dom elements?</p>
  
  <p><strong>My ideas so far:</strong></p>
  
  <pre><code>1.
  &lt;div class="standard_chart"
       chart_title="Trend of X vs. Y"
       data_url="/data/x_vs_y"
       pre_process_fn="...some js code..."&gt;&lt;/div&gt;
  // then use `eval` to use the js code in the attribute
  
  
  2.
  &lt;div class="standard_chart"
       chart_title="Trend of X vs. Y"
       data_url="/data/x_vs_y"
       pre_process_fn="...some js code..."&gt;
      &lt;pre_process_fn&gt;
          &lt;script&gt;... function definitions ... &lt;/script&gt;
      &lt;/pre_process_fn&gt;
  &lt;/div&gt;
  // then somehow get and associate the js internal to the element
  </code></pre>
  
  <p>I'm not sure what the other options are, and what their relative benefits are.</p>