...

View Full Version : Passing 'this' to an anonymous function in an event listener



Malcolm
06-10-2010, 09:25 PM
Hello!

I'm working with nested functions and trying to pass a 'this' value to an anonymous being used in an assignment for an event listener. Here's the basics of my code:


<div id='abc'></div>
<script type='text/javascript'>
var abc = function () {
this.myFunction = function() {
var myObj
myObj = document.createElement("input");
myObj.setAttribute("type", "button");
myObj.setAttribute("value", "Click Me");
myObj.addEventListener("click", function () {
this.doDing();
}, false);
document.getElementById('abc').appendChild(myObj);
}
this.doDing = function () { alert('ding'); }
}
var myInstance = new abc();
myInstance.myFunction();
</script>

So, this should plop a button inside our DIV and when clicked I'd like it to run the alert-ding; unfortunately it seems to want to run the function as defined under the buttons object which doesn't work out too well.

Any suggestions?

Thanks!

gusblake
06-10-2010, 10:06 PM
I think you'd have to do it like this:



var abc = function () {
this.myFunction = function() {
var myObj
var abcinst=this;
myObj = document.createElement("input");
myObj.setAttribute("type", "button");
myObj.setAttribute("value", "Click Me");
myObj.addEventListener("click", function () {
abcinst.doDing();
}, false);
document.getElementById('abc').appendChild(myObj);
}
this.doDing = function () { alert('ding'); }
}
var myInstance = new abc();
myInstance.myFunction();

Malcolm
06-10-2010, 10:25 PM
Yep, that works. I was hoping to do the something that wouldn't make another copy of the object in memory.

Thanks!


Edit:
Oh, I lie, this creates a reference to the object and uses no additional memory.

Dormilich
06-11-2010, 07:38 AM
there’s an even easier solution for your case.

var abc = function () {
this.myFunction = function() {
var myObj
myObj = document.createElement("input");
myObj.setAttribute("type", "button");
myObj.setAttribute("value", "Click Me");
myObj.addEventListener("click", this.doDing, false);
document.getElementById('abc').appendChild(myObj);
}
this.doDing = function () { alert('ding'); }
}
var myInstance = new abc();
myInstance.myFunction();

it works because there’s no this in .doDing()



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum