Problem using object methods as event handlers

Problem using object methods as event handlers

Post by D. Patters » Sat, 05 Nov 2005 09:55:34


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
 
 
 

Problem using object methods as event handlers

Post by Richard Co » Sat, 05 Nov 2005 11:30:56


Not at all an unusual desire.

<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.yqcomputer.com/ ;

Richard.

 
 
 

Problem using object methods as event handlers

Post by D. Patters » Sun, 06 Nov 2005 00:01:48

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

Thanks
Dave