473,322 Members | 1,614 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

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


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

Jul 23 '05 #1
5 1687
nu*****@naver.com wrote:
========= 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.

Jul 23 '05 #2
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/comp.lang.javascript/browse_frm/thread/5f7aaccb9f46722f/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('oncli ck',obj.clickMethod);
</script>
</body>
</html>

Jul 23 '05 #3
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>

Jul 23 '05 #4
On 31/05/2005 15:47, nybble wrote:

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


Why are you processing events in the capturing phase?

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
VK wrote:
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
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Pavils Jurjans | last post by:
Hallo, I have been programming for restricted environments where Internet Explorer is a standard, so I haven't stumbled upon this problem until now, when I need to write a DOM-compatible code. ...
10
by: SunshineGirl | last post by:
In my code, class A instanciates classes B and C. I would like class B to connect an event handler to a method in class A, and for class C to disconnect that event handler. I think I've done...
1
by: malcolm | last post by:
Is there a way to test to see if an event handler hasn't already been added to an event handler listener object? This is what I am doing now as a hack: dataView.ListChanged -= new...
5
by: DC Gringo | last post by:
I've got a command button to submit a value from a dropdown list that should then filter a SELECT query. I'm simply appending a WHERE colx = <variableSelectedFromDropdownList>. How do I pass this...
3
by: moondaddy | last post by:
C# 2.0 I have declared some event arguments like this: public class ModeStateChangedEventArgs : EventArgs { Gen.DataState myState; public ModeStateChangedEventArgs() { }
2
by: Ralph | last post by:
Hi I don't understand why it's not working: function schedule(imTop){ this.tdImagesTop = imTop; } schedule.prototype.selectEl = function() { alert(this.tdImagesTop);
4
by: eggie5 | last post by:
I have this even handler (using prototype.js): showCommentsLinks.observe('click', function(event) { alert('hi') }); It's attaching to a link element: <a id="showCommentsLink"...
3
by: wolverine | last post by:
Hi, I am injecting a javascript code into html pages and attaching some dom events to some elements via attachEvent (IE only). I just want to know that is there any chance by which my event...
24
by: =?Utf-8?B?U3dhcHB5?= | last post by:
Can anyone suggest me to pass more parameters other than two parameter for events like the following? Event: Onbutton_click(object sender, EventArgs e)" Event handler: button.Click += new...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.