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

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.getElementsByTagName('DIV');
for (i=0; i<arr.length; i++) {
arr[i].addEventListener(
'click',function(e){myFunction(arr[i],e);},true);
}
}

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

<body bgcolor="#FFFFFF" onload="init()">
<div id='d1'>Some <a href="javascript:void(0)" id='s1'>link</a></div>
<div id='d2'>Some <a href="javascript: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.getElementsByTagName('DIV');
var foo = null;
for (i=0; i<arr.length; i++) {
foo = arr[i];
arr[i].addEventListener(
'click',function(e){myFunction(foo,e);},true);
}
}

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

Jul 23 '05 #1
7 1347
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>Untitled 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.getElementsByTagName('DIV');
for (i=0;i<tmp.length;i++) {
// filling up the global array from the collection:
glbArray.push(tmp[i]);
}
for (i=0; i<glbArray.length; i++) {
//
glbArray.addEventListener('click',function(e){myFu nction(glbArray[i],e);},true);
// ^ NOOP !!! myFunction gets undefined
foo = glbArray[i];
foo.addEventListener('click',function(e){myFunctio n(foo,e);},true);
// ^ Works like a charm !!!
}
}

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

<body bgcolor="#FFFFFF" onload="init()">
<div id='d1'>Some <a href="javascript:void(0)" id='s1'>link</a></div>
<div id='d2'>Some <a href="javascript: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.getElementsByTagName('DIV');
for (i=0; i<arr.length; i++) {
arr[i].addEventListener(
'click',function(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 addEventListener, or the on<type> properties, the better approach is:

function init() {
var arr = document.getElementsByTagName('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].addEventListener('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.getElementsByTagName('DIV');
for (i=0; i<arr.length; i++) {
arr[i].addEventListener(
'click',function(e){myFunction(arr[i],e);},true);
}
}
The function passed to abbEventListener 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.getElementsByTagName('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].addEventListener(
'click',function(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.javascript/browse_frm/thread/5f7aaccb9f46722f/a5395b4a5dd6472b#a5395b4a5dd6472b>

for (...) {
assignHandler(arr[i]);
}

and:

function assignHandler(obj) {
obj.addEventListener('click', function(e){processClick(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**********@yahoo.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/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #7
"Richard Cornford" <Ri*****@litotes.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/rasterTriangleDOM.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
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...
6
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...
3
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,...
6
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...
8
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: - - - - - - - - ...
5
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...
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. ...
14
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...
14
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...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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:
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...
0
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,...
0
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...
0
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...
0
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,...

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.