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
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