473,594 Members | 2,984 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Broken object referencing from within an array?

VK
.... or my script, or my mind, or both?

<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script>
function init() {
var arr = document.getEle mentsByTagName( 'DIV');
for (i=0; i<arr.length; i++) {
arr[i].addEventListen er(
'click',functio n(e){myFunction (arr[i],e);},true);
}
}

function myFunction(obj, evt) {
alert(obj.id);
}
</script>
</head>

<body bgcolor="#FFFFF F" onload="init()" >
<div id='d1'>Some <a href="javascrip t:void(0)" id='s1'>link</a></div>
<div id='d2'>Some <a href="javascrip t:void(0)" id='s2'>link</a></div>
</body>
</html>
The above simply doesn't work - myFunction gets undefined as obj ! But
with a bogus intermediary var it works like a charm:

function init() {
var arr = document.getEle mentsByTagName( 'DIV');
var foo = null;
for (i=0; i<arr.length; i++) {
foo = arr[i];
arr[i].addEventListen er(
'click',functio n(e){myFunction (foo,e);},true) ;
}
}

All the same in IE (with attachEvent). What a hey?

Jul 23 '05 #1
7 1365
VK
The mistery is growing... I thought that maybe this way I was working
with a collection object and not with a "blue blood" array, and it
might cause some strange problem. So I did this profoundly idiotic
algorithm just to be 100% sure I'm working with a real global array:

<title>Untitl ed Document</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script>
// Declaring a global array variable:
var glbArray = new Array();

function init() {
var foo = null;
var tmp = document.getEle mentsByTagName( 'DIV');
for (i=0;i<tmp.leng th;i++) {
// filling up the global array from the collection:
glbArray.push(t mp[i]);
}
for (i=0; i<glbArray.leng th; i++) {
//
glbArray.addEve ntListener('cli ck',function(e) {myFunction(glb Array[i],e);},true);
// ^ NOOP !!! myFunction gets undefined
foo = glbArray[i];
foo.addEventLis tener('click',f unction(e){myFu nction(foo,e);} ,true);
// ^ Works like a charm !!!
}
}

function myFunction(obj, evt) {
alert(obj.id);
}
</script>
</head>

<body bgcolor="#FFFFF F" onload="init()" >
<div id='d1'>Some <a href="javascrip t:void(0)" id='s1'>link</a></div>
<div id='d2'>Some <a href="javascrip t:void(0)" id='s2'>link</a></div>
</body>
</html>

All the same with IE. Any light?

Jul 23 '05 #2
On 30/05/2005 12:16, VK wrote:
... or my script, or my mind, or both?
Don't assume that a subject has been, or can be, read in full.
<script>
The type attribute?
function init() {
var arr = document.getEle mentsByTagName( 'DIV');
for (i=0; i<arr.length; i++) {
arr[i].addEventListen er(
'click',functio n(e){myFunction (arr[i],e);},true);
}
}
When a closure is created, it doesn't take a snapshot of the variables
in its scope chain - they remain live. By the time the listener is
invoked, i will 'point' beyond the defined array contents, providing
undefined to myFunction.

With addEventListene r, or the on<type> properties, the better approach is:

function init() {
var arr = document.getEle mentsByTagName( 'div');

for(var i = 0, n = arr.length; i < n; ++i) {

/* Unless you have a reason to use
* event capturing, don't bother.
*
* The capturing phase should only
* be used to intercept events
* before 'normal' event listeners
* receive the event.
*/
arr[i].addEventListen er('click', myFunction, false);
}
}
function myFunction(e) {
/* The this operator will refer
* to the correct DIV element.
*/
alert(this.id);
}

Unfortunately this won't work with Microsoft's attachEvent mechanism
(the this operator isn't set correctly), which is why it's broken and I
never use it.

[snip]
But with a bogus intermediary var it works like a charm:
No it doesn't.

[snip]
for (i=0; i<arr.length; i++) {
foo = arr[i];


The foo variable will always refer to the last DIV element encountered.
Click the first link in your example and this is obvious.

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
VK wrote:
<snip>
function init() {
var arr = document.getEle mentsByTagName( 'DIV');
for (i=0; i<arr.length; i++) {
arr[i].addEventListen er(
'click',functio n(e){myFunction (arr[i],e);},true);
}
}
The function passed to abbEventListene r is executed long after the loop
has finished executing, and when the containing function's local
variable - i - has been incremented beyond the range of the contents of
the - arr - collection.
The above simply doesn't work - myFunction gets undefined as obj !
Yes, the contents of - arr[arr.length] - are undefined, and - i ==
arr.length - at the end of the loop.
But
with a bogus intermediary var it works like a charm:
You really should test these things a bit less superficially before
making that type of statement. The local variable - foo - always
contains a reference to the same DOM element regardless of how many
event listeners were attached, and which is executed.
function init() {
var arr = document.getEle mentsByTagName( 'DIV');
var foo = null;
for (i=0; i<arr.length; i++) {
foo = arr[i];
This assignment happens - arr.length - times, and the last assignment
sets the value of - foo - that the event handlers will be using.
arr[i].addEventListen er(
'click',functio n(e){myFunction (foo,e);},true) ;
}
}

All the same in IE (with attachEvent). What a hey?


Closures!

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

Richard.
Jul 23 '05 #4
VK
> You really should test these things a bit less superficially
before making that type of statement.

- Sorry, I really was in rush

I solved the problem by moving the handler assignement out of the loop:
<http://groups-beta.google.com/group/comp.lang.javas cript/browse_frm/thread/5f7aaccb9f46722 f/a5395b4a5dd6472 b#a5395b4a5dd64 72b>

for (...) {
assignHandler(a rr[i]);
}

and:

function assignHandler(o bj) {
obj.addEventLis tener('click', function(e){pro cessClick(obj, e);});
}

I guess it's one of these rather rare situations when the programming
logic goes against the human one.
However it was with closures (I guess there are reasons for them to be
such), it's still "strange" that the program resolves obj at the
function creation time, but refuses to do the same for arr[i] (an array
element).

Jul 23 '05 #5
VK wrote:
<snip>
I guess it's one of these rather rare situations when
the programming logic goes against the human one.
Speak for yourself. The scope structure in javascript is completely
logical, mechanically and in the perception of (most) humans.
However it was with closures (I guess there are reasons
for them to be such), it's still "strange" that the program
resolves obj at the function creation time, but refuses to
do the same for arr[i] (an array element).


Just once it would be nice if you would actually go and read the
resources that people refer you to. You might then eventually get into a
position where some of what you think is not twaddle.

Richard.
Jul 23 '05 #6
"VK" <sc**********@y ahoo.com> writes:
However it was with closures (I guess there are reasons for them to be
such), it's still "strange" that the program resolves obj at the
function creation time, but refuses to do the same for arr[i] (an array
element).


Not so strange. There is only one "i" variable, and all the closures
refer to that one. When it changes its value, it affects all closures.
However, since "obj" is a formal parameter of a function, there is
effectively a new variable for each call. It never varies, and each
closure refers to its own version.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #7
"Richard Cornford" <Ri*****@litote s.demon.co.uk> writes:
Speak for yourself. The scope structure in javascript is completely
logical, mechanically and in the perception of (most) humans.


The scope structure is fine and logical, it's just its interaction
with variables that won't feel natural to me. Probably because I
learned closures in a functional language where variables didn't,
well, *vary* very much. :)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #8

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

Similar topics

2
3928
by: Dicky Cheng | last post by:
Hi, I am using .net remoting technology. I set up a .net remoting client and server in IIS. When the client calls the server, the server will run a long duration method (30-60seconds). I have a test on it that if the network broken at the time the client have already send the remoting request and waiting for the server, the client side will wait infinitely by default, even if i already set the executionTimeout to 90seconds in...
6
15202
by: marktm | last post by:
Hi- I am trying to use setInterval to call a method within an object and have not had any luck. I get "Object doesn't support this property or method" when I execute the following code. What I am doing wrong? Your help will be much appreciated. Thanks
3
3440
by: ozbear | last post by:
This is probably an obvious question. I know that pointer comparisons are only defined if the two pointers point somewhere "into" the storage allocated to the same object, or if they are NULL, or one-past the end of the object as long as it isn't dereferenced. I use "object" in the standard 'C' sense. Is there some special dispensation given to comparing two pointers
6
2076
by: frankplank | last post by:
Hi *, I'm wondering if it is possible to create a C# object, and reference it *explicitly* in an excel document. I imagine this will be more possible if I programmatically populate the excel sheet cells, but I would like to avoid this. I'm thinking something like this: object1: DataArray ...; GetValue(StringVal) ; // get value of data array, based on string
8
1861
by: wASP | last post by:
Hi, I'm having a problem referencing the elements within an object after a method of that object (a member function) has been activated with an onsubmit handler: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <script language="javascript" type="text/javascript"> function js_onsubmit_hndl_fn () {
5
6450
by: Varangian | last post by:
ImageButton ship; ship = new ImageButton; for (int i=0; i<5; i++) { ship.ImageUrl = pathofImage; ship.ID = "ShipNo" + i.ToString(); ship.Click += new ImageClickEventHandler(this.ImageBtn_Click); this.Form1.Controls.Add(ship); }
12
5536
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. Foo = function(type) { this.num = 0; this.type = type this.trigger(); } Foo.prototype.trigger = function() {
14
2564
by: Jeroen | last post by:
Hi all, I've got a question about writing a library. Let me characterize that library by the following: * there is a class A which is available to the user * there is a class B that is used in severel 'underwater operations' * there is a list which stores objects of class B There are several issues I'm not sure about:
14
1443
by: Summercool | last post by:
The meaning of a = b in object oriented languages. ==================================================== I just want to confirm that in OOP, if a is an object, then b = a is only copying the reference. (to make it to the most basic form: a is 4 bytes, let's say, at memory location 0x10000000 to 0x10000003
0
8253
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
8374
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...
1
8009
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6661
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5739
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
5411
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
3903
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2389
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
1
1482
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.