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?
- <script>
- function constrainTextarea(ele,maxlength)
- {
- this.ele = $("#"+ele);
- this.maxlength=maxlength;
-
- this.listen = function(){
- alert("I'm listening! "+this.ele.attr('id'));
- };
- this.unlisten = function(){
- alert("stop listening "+this.ele.attr('id'));
- };
-
- $(this.ele).focus(function(e){self.listen();});
- $(this.ele).blur(function(e){self.unlisten();});
- }
- $(document).ready(function(){
- cta1 = new constrainTextarea('ta1',200);
- cta2 = new constrainTextarea('ta2',200);
- });
- </script>
- <textarea id=ta1></textarea>
- <textarea id=ta2></textarea>