Attaching an Event Handler(my own Object Method) ??

N

nukiboy

========= test.js ===================

function Test()
{
this.temp = "hehehehe" ;

this.method1 = method1 ;



}
function method1()
{
alert(this.temp) ;

}

========= test.html =====================

<BODY>

<a id="test">aaaaaaaa</a>
<script>

var obj = new Test(window) ;

document.all['test'].attachEvent("onclick",obj.testMethod) ;

</script>
</BODY>

Result :

This Alert "undefined" !!!

What?

Can't I attach my Own Object Method to Target ?

Please post the answer!!
 
R

Random

========= test.js ===================

function Test()
{
this.temp = "hehehehe" ;

this.method1 = method1 ;



}
function method1()
{
alert(this.temp) ;

}

========= test.html =====================

<BODY>

<a id="test">aaaaaaaa</a>
<script>

var obj = new Test(window) ;

document.all['test'].attachEvent("onclick",obj.testMethod) ;

</script>
</BODY>

Result :

This Alert "undefined" !!!

What?

Can't I attach my Own Object Method to Target ?

Please post the answer!!

Short answer:
Saying:
a = b;
c = b;

is the same as saying:
c = a;

Except for the wasted effort.

If I say:
x = new Object();
x.method = someFunc;

Then I say:
document.getElemetById( 'test' ).attachEvent(
'onclick', x.method );

It is roughly the same as saying:
document.getElementById( 'test' ).attachEvent(
'onclick', someFunc );



The rest of this post is superfluous, just in case you need a long
explanation of the above:

You declare a function:
function method1( ) {

You tell it to popup a message displaying the value of a variable. In
particular, the value of the .temp member of whatever object may
constitute 'this'.

You then create an object.
var obj = new Test( window );

First: the reference to 'window' here is superfluous. If you're not
using it, get rid of it.

More importantly, what this does is instantiate a new Object object and
calls the constructor function Test().

Test does this:
It assigns a String value to the 'temp' member of the new Object
object.
It assigns a reference to the method1 function to the 'method1' member
of the new Object object.


So if you call it in this way:
obj.method1()
Then 'this' refers to 'obj'.


Your code above says:
document.all['test'].attachEvent("onclick",obj.testMethod) ;

I assume you meant:
document.all['test'].attachEvent("onclick",obj.method1);

Because you never defined any 'testMethod' anywhere in the entire
document.

What this revised version does is assigns a reference to the the
method1 function to be the onclick event handler of the 'test' element.
This is the same as assigning it as a method of the HTMLElement object
in question.

Same thing as you did when you assigned it to the new Test object,
isn't it?

So when onclick gets called, what will happen?
It is called as:
document.all['test'].onclick();

So 'this' will refer to the HTML element called 'test'.


Probably not a very good explanation. I'm tired. You'll get better
answers within the next few hours I'm sure.
 
V

VK

I guess on the university language it's called "switching the execution
context"(?) On my language it's called "when THIS becomes THAT" (means
it points to something you did not expect at all). :)

In your situation THIS points to the surrent window, and it indeed
doesn't have any "hehehe" in it.
You have to use either the abbreviated form: obj.field (naturlich that
the "obj" has to be global) or the full statement: this.obj.field

Also please note that your code in miserably IE-dependent and it will
fail on any more-or-less complicated situation (when your element
contains any nested elements in it).
Try my algorythm from
<http://groups-beta.google.com/group...ccb9f46722f/a5395b4a5dd6472b#a5395b4a5dd6472b>

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script>
function Test() {
this.field = 'hehehe';
this.clickMethod =
function() {
alert(obj.field);
}
}
</script>
</head>

<body bgcolor="#FFFFFF">
<div id="div1">DIV 1</div>
<script>
var obj = new Test();
document.getElementById('div1').attachEvent('onclick',obj.clickMethod);
</script>
</body>
</html>
 
N

nybble

As random points out - you are trying to call a function directly,
instead of calling a method on an object. I'm guessing that this is
just a simplified example for an object with more complexity -
otherwise it's probably easier to just forget the object and make a
function directly.

But, if you need to use an object, here's three ways (of probably many)
to do it. Depending on your needs. Div1 attaches a function that
creates an object and then calls the method on each click, Div2
attaches a function that uses a top level object to call the method on,
and Div3 attaches a closure with an object built in. I suspect Div2 is
probably what you are after - if you need an object once, you probably
want to be able to use it elsewhere, too.

Anyhow, this code works in firefox you'll need to reconvert it back to
ie. :)

<script>
function Test(msg) {
this.field = msg;
}
Test.prototype.method = function () { alert(this.field) };

function makeClosure (msg) {
var testobj = new Test(msg);
return function () { testobj.method() }
}

var div3func = makeClosure('this is div 3');
var testobj = new Test( 'this is div 2');
</script>

<div id="div1">DIV 1</div>
<div id="div2">DIV 2</div>
<div id="div3">DIV 3</div>
<script>
document.getElementById('div1').addEventListener('click',function () {
var x = new Test('this is div1'); x.method() },true);
document.getElementById('div2').addEventListener('click',function () {
testobj.method() },true);
document.getElementById('div3').addEventListener('click',div3func,
true);
</script>
 
M

Michael Winter

On 31/05/2005 15:47, nybble wrote:

[snip]
[...] addEventListener('click', [...] ,true);

Why are you processing events in the capturing phase?

[snip]

Mike
 
T

Thomas 'PointedEars' Lahn

VK said:
I guess on the university language it's called "switching the execution
context"(?)

It's called "Quote (the heck) the minimum of what you are referring to!"
and "different variable object" in this newsgroup and among educated
ECMAScript/JS programmers.
On my language it's called "when THIS becomes THAT" [...]

How descriptive.


PointedEars
 

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,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top