title: object oriented jquery - event handlers not working
body: <p>I am moving some jquery functions into a javascript object to clean up some code. My problem is, when I put methods on my object's constructor, my event handlers don't seem to respond to events but respond fine if my handlers are <em>helper methods</em> and are outside of the object's constructor. </p>
  
  <p>Here's my code that isn't working</p>
  
  <pre><code>function MyConstructor() {
      this.init();
      this.selectAllHandler();
  }
  
  MyConstructor.prototype = {
    init: function() {
      $(document).on('click', '#my_element', this.selectAllHandler);
    },
    selectAllHandler: function() {
      // some code in here
    }
  }
  </code></pre>
  
  <p>When using this, my code does not error out and putting <code>console.log</code>'s atop the function runs. But when I try to click on the thing to trigger the handler, it doesn't do anything. </p>
  
  <p>But, if I build it as a constructor using a method outside of the object, it works fine. Like this</p>
  
  <pre><code>function MyConstructor() {
      this.init();
  }
  
  MyConstructor.prototype = {
    init: function() {
      $(document).on('click', '#my_element', selectAllHandler);
    }
  }
  
  function selectAllHandler() {
    // code that works fine
  }
  </code></pre>
  
  <p>what am I doing wrong that I cannot call the handlers inside the object's prototype?</p>
  
  <p><strong>edit</strong></p>
  
  <p>Here is my new code. The problem now, is <code>$(this)</code> seems to refer to the constructor and no longer refers to the element being clicked on. </p>
  
  <pre><code>function MyConstructor() {
    this.init();
  }
  
  MyConstructor.prototype = {
    init: function() {
      $(document).on('click', '#my_element', this.selectAllHandler.bind(this));
    },
      selectAllHandler: function() {
          var checkboxes = $('.prospect_select_box');
  
          console.log($(this)); // =&gt; [MyConstructor]
  
          if (!$(this).prop('checked')) {
              console.log('here')
              checkboxes.prop('checked', false);
              $('#prospect-left-section').hide();
          } else {
              console.log('other here')
              checkboxes.prop('checked', true);
              $('#prospect-left-section').show();
          }
      }
  }
  </code></pre>