Assigning elements to classes to control events

Assigning elements to classes to control events

I'm trying to use a javascript class to assign specific event handlers to different elements. I create an object and pass it a reference to the element, and some properties for the event handler to use. When the event fires, I want the handler to reference the properties of the object. But I'm clearly doing something wrong as multiple instances all refer to the most recent object only.

Any pointers?

  1. <script>
  2. function constrainTextarea(ele,maxlength)
  3. {
  4. this.ele = $("#"+ele);
  5. this.maxlength=maxlength;
  6. this.listen = function(){
  7. alert("I'm listening! "+this.ele.attr('id'));
  8. };
  9. this.unlisten = function(){
  10. alert("stop listening "+this.ele.attr('id'));
  11. };
  12. $(this.ele).focus(function(e){self.listen();});
  13. $(this.ele).blur(function(e){self.unlisten();});
  14. }

  15. $(document).ready(function(){
  16. cta1 = new constrainTextarea('ta1',200);
  17. cta2 = new constrainTextarea('ta2',200);
  18. });

  19. </script>
  20. <textarea id=ta1></textarea>
  21. <textarea id=ta2></textarea>