473,808 Members | 2,832 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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">aaaaa aaa</a>
<script>

var obj = new Test(window) ;

document.all['test'].attachEvent("o nclick",obj.tes tMethod) ;

</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 1709
nu*****@naver.c om wrote:
========= test.js =============== ====

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

this.method1 = method1 ;

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

}

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

<BODY>

<a id="test">aaaaa aaa</a>
<script>

var obj = new Test(window) ;

document.all['test'].attachEvent("o nclick",obj.tes tMethod) ;

</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.getEle metById( 'test' ).attachEvent(
'onclick', x.method );

It is roughly the same as saying:
document.getEle mentById( '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("o nclick",obj.tes tMethod) ;

I assume you meant:
document.all['test'].attachEvent("o nclick",obj.met hod1);

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.javas cript/browse_frm/thread/5f7aaccb9f46722 f/a5395b4a5dd6472 b#a5395b4a5dd64 72b>

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

<body bgcolor="#FFFFF F">
<div id="div1">DIV 1</div>
<script>
var obj = new Test();
document.getEle mentById('div1' ).attachEvent(' onclick',obj.cl ickMethod);
</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.fiel d) };

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

var div3func = makeClosure('th is 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.getEle mentById('div1' ).addEventListe ner('click',fun ction () {
var x = new Test('this is div1'); x.method() },true);
document.getEle mentById('div2' ).addEventListe ner('click',fun ction () {
testobj.method( ) },true);
document.getEle mentById('div3' ).addEventListe ner('click',div 3func,
true);
</script>

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

[snip]
[...] addEventListene r('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
49588
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. The question is about best practices for passing parameters to an event function. I have, say, the following HTML:
10
3500
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 too much thinking, and now I'm even more confused as to how to accomplish this as when I started. Any help will be appreciated.
1
5006
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 ListChangedEventHandler(dataView_ListChanged); dataView.ListChanged += new ListChangedEventHandler(dataView_ListChanged);
5
1807
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 value into the event handler? -- MY EVENT HANDLER Sub RunReport_OnClick(sender As Object, e As System.EventArgs) _sqlStmt = _sqlStmt & " AND colx = '<variableSelectedFromDropdownList>'"
3
1577
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
2662
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
2142
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" href="comments/">Show Comments</a>
3
2367
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 handler not getting executed ? ie, is there some means for the web developer to prevent any further handler getting executed for the same event on the same element ? To be more clear, assume the web developer has attached function "f1()" on onclick...
24
55246
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 EventHandler(Onbutton_click); I want to pass more information related that event. & want to use that
0
9600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10631
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10114
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6880
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5548
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4331
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3011
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.