473,385 Members | 1,356 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,385 software developers and data experts.

object reference in event handlers

Something that's been bugging me for a while: I can't figure out how to
register an object method as an event handler, and still use the 'this'
keyword inside the handler to refer to the object. For example:

function myObj ()
{
this.toString = function(){return 'myObj'}; //define string
representation of this object
document.getElementById('test_tag_id').onclick = this.test; //attach
to some clickable element
}
myObj.prototype.test = function()
{
alert('object: ' + this);
}
tmp = new myObj(); //instantiate
tmp.test(); //verify the function works normally ... should report
'object: myObj'

Now, when I click on the object, the alert dialog reports 'object:
[object HTMLTableElement]'. Any ideas?

Jul 23 '05 #1
3 1613
If I replace this.test; with
function(obj) { return function() { obj.test.apply(obj); }; } (this);
it works as you've asked.

Csaba Gabor from Vienna

cainlevy wrote:
Something that's been bugging me for a while: I can't figure out how to
register an object method as an event handler, and still use the 'this'
keyword inside the handler to refer to the object. For example:

function myObj ()
{
this.toString = function(){return 'myObj'}; //define string representation of this object
document.getElementById('test_tag_id').onclick = this.test; //attach to some clickable element
}
myObj.prototype.test = function()
{
alert('object: ' + this);
}
tmp = new myObj(); //instantiate
tmp.test(); //verify the function works normally ... should report 'object: myObj'

Now, when I click on the object, the alert dialog reports 'object:
[object HTMLTableElement]'. Any ideas?

Jul 23 '05 #2
On 07/04/2005 06:06, cainlevy wrote:
Something that's been bugging me for a while: I can't figure out how to
register an object method as an event handler, and still use the 'this'
keyword inside the handler to refer to the object. For example:
The value of the this operator varies based on the circumstances in
which it's used. Within the body of a function, the this operator
takes on two possible value types: a reference to the global object,
or a reference to an object.

If the function is called directly, for example

var myFunction = myObj.myMethod;

myFunction();

the this operator will "point" to the global object. If the function
object is called through a property accessor, for example

myObj.myMethod();

the this operator will "point" to the referenced object; myObj in this
case.
this.toString = function(){return 'myObj'};
Unless the returned string changes, this too should be placed on the
prototype object.
document.getElementById('test_tag_id').onclick = this.test;


Here, you assign a function reference to a property of a different
object. When that function is invoked, it is done so as a property of
this new object. That's why you have a reference to the table, and not
the original object.

You might work around this in two ways:

1) Assign a reference to the original object to the element. You can
then use this reference in your listener code.

myObj.myMethod = function() {
/* Use
*
* this.obj
*
* to refer to myObj.
*/
};

element.obj = myObj;
element.onclick = myObj.myMethod;

2) Use a closure. There is more than one solution using this
approach. One might be:

function MyObj() {
var self = this;

this.myMethod = function() {
/* Use self to refer to an instance of MyObj,
* irrespective of how this function is called.
*/
};
}

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
cainlevy wrote:
Something that's been bugging me for a while: I can't figure
out how to register an object method as an event handler,
and still use the 'this' keyword inside the handler to refer
to the object. ...

<snip>
Numerous techniques are in more or less common use, including the one
described in the note associated with this group's FAQ:-

<URL: http://jibbering.com/faq/faq_notes/closures.html#clObjI >

- which is probably the simplest to implement and the4 hardest to
understand.

Richard.
Jul 23 '05 #4

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

Similar topics

3
by: RobG | last post by:
I am playing with a script that will allow columns of a table to be moved by dragging them left or right. To do this with functions is fairly straight forward, however after looking at Richard...
8
by: Dennis C. Drumm | last post by:
I have a class derived from a SortedList called SystemList that contains a list of objects indexed with a string value. The definition of the objects contained in the SortedList have a boolean...
2
by: films | last post by:
I understand the concept. Serialization of a class will add all the sub-objects of the class to the stream if there are also serializible. So say I have: class Author {
2
by: Giovanni Bassi | last post by:
Hello All, I have encountered a problem. I am using visual inheritance and my base form adds an event handler on Form Load using the AddHandler Keyword. The problem is that if the Event...
5
by: Michael Moreno | last post by:
Hello, In a class I have this code: public object Obj; If Obj is a COM object I would like to call in the Dispose() method the following code: ...
16
by: anonymous.user0 | last post by:
The way I understand it, if I have an object Listener that has registered as a listener for some event Event that's produced by an object Emitter, as long as Emitter is still allocated Listener...
12
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. ...
6
by: Shailen Sukul | last post by:
Observed a weird behaviour with object references. See code listing below: using System; using System.Collections.Generic; using System.Text; namespace PointerExceptionTest { /*
6
by: Murray Hopkins | last post by:
Hi. THE QUESTION: How do I get a reference to my Object when processing an event handler bound to an html element ? CONTEXT: Sorry if it is a bit long. I am developing a JS calendar tool....
4
by: Joergen Bech | last post by:
I sometimes use delegates for broadcasting "StateChanged" events, i.e. if I have multiple forms and/or controls that need updating at the same time as the result of a change in a global/common...
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...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.