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>

The values in the assigned function bear no relation to the values outside of the function.

This code:


this.listen = function() {
    alert("I'm listening! "+this.ele.attr('id'));
};

does the same as this code:


function listenHandler() {
    alert("I'm listening! "+this.ele.attr('id'));
};

this.listen = listenHandler;

Now it’s easier to tell that the function only knows about the variables at the time the function is called.

What you can do about that is to invoke a function and pass that variable to it. When you then return a function from inside that invoked one, the returned function retains knowledge of the passed variable.


function listenHandler() {
    alert("I'm listening! "+ele.attr('id'));
};

this.listen = function (ele) {
    return listenHandler;
}(this.ele);

You can then condense that down to the following:


this.listen = function (ele) {
    return function () {
        alert("I'm listening! "+ele.attr('id'));
    };
}(this.ele);