PDA

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



Mal
06-10-2010, 07:45 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.

Any suggestions?

Thanks!

vwphillips
06-11-2010, 08:38 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
</head>

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

</html>