Problem using object methods as event handlers

D

D. Patterson

Hello all.

I've a bit of a problem. I would like to use a method in an object as an
event handler. Unfortunately, when the method is called the "this" object
references the event trigger rather than my object.

For example, with the following code, an alert will be shown when the page
loads
where the value of my_name is "My Object" and nodeName is 'undefined".
Dismissing
that alert and then clicking anywhere on the page will present another alert
where the
value of my_name is "undefined" and the value of nodeName is "BODY".

<html>
<head>
<title>Event Example</title>
<script type="text/javascript" language="JavaScript">
function x( n )
{
this.my_name = n;
}
x.prototype.toString = function( level ){ return "ABC"; }
x.prototype.event_handler = function( e )
{
var evt = ( e ? e : ( window.event ? window.event : null ));
if( !evt ) return;
alert( "x.event_handler()\n" +
" my_name:\t" + this.my_name + "\n" +
" nodeName:\t" + this.nodeName + "\n" +
" event:\t\t" + evt.type );
}

function body_onload()
{
my_obj = new x( "My Object" );
my_obj.event_handler( { type:'Dummy' } );
document.body.onclick = my_obj.event_handler;
}
</script>
</head>
<body onload="body_onload();">
<input id="Button1" name="Button1" type="button" value="Button 1">
</body>
</html>

Any suggestions as to how to get around this?

Thanks in advance.,

Dave
 
R

Richard Cornford

D. Patterson said:
I've a bit of a problem. I would like to use a method in an object as
an event handler.

Not at all an unusual desire.
Unfortunately, when the method is called the "this"
object references the event trigger rather than my object.
<snip>

There are a number of techniques that handle this problem. As you are
assigning the handlers as a function reference the most appropriate
method is described here:-

<URL: http://www.jibbering.com/faq/faq_notes/closures.html >

Richard.
 
D

D. Patterson

Wow. Great article.
Now I go play for a while.
I'll post the results....later.

Thanks
Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top