title: Pattern for widgets in unobstructive javascript
body: <p>I'm using JS and jQuery for the first time after a lot of experience with Java and C++. I'm loving jQuery's idea of <code>$(document).on('click', 'btn-selector', react)</code>, but for more complex widgets I'm finding myself in the same rut over and over: in each <code>react</code> handler, I have to look up the widget as a whole and reconstruct all my knowledge about it.</p>
  <p>For example, I'm making a simple widget out of <code>&lt;input&gt;</code>s with which the user can make a grading scale: 90 maps to an A, 80 maps to a B, etc.  When one of the inputs changes, I want to check to make sure that the inputs are still in order (your scale can't go 90, 70, 80, for example).</p>
  <p>So, I have something like</p>
  <h1>Actual</h1>
  <pre><code>$(document).on('click', '.scale-input', function() {
      var widget = $(this).closest('.scale-widget-container');
      ensureLevelsAreInOrder(widget);
  });
  </code></pre>
  <p>Almost every single handler has to have this first line to find its context.  I'd much rather have code that looks like this:</p>
  <h1>Preferred</h1>
  <pre><code>$(document).on('click', '.scale-input', ensureLevelsAreInOrder);
  </code></pre>
  <p>The problem is that in this form, <code>ensureLevelsAreInOrder</code> only has a reference to the input that changed, not the larger context.</p>
  <p>In Java or C++, I would have called a constructor on the widget, and each input would have a handler with the context baked in via member variables.  I could do something similar with</p>
  <pre><code>$(function() {
      $('.scale-widget-container').scaleWidget();
  });
  </code></pre>
  <p>with <code>scaleWidget()</code> setting up the contextualized handlers, but the page I'm working with loads a lot of its html with ajax and I don't have a reliable time to run that initialization.</p>
  <p>Is this a common problem that we just have to deal with if we don't want JS in our HTML, or is there a solution I haven't come across yet?</p>