...

View Full Version : JSON object loop



Kor
05-01-2006, 08:36 PM
To return, onsomeevent, the index of some elements (HTML) in their collection, I use a 'faux' attribute, ex:


var myEl =document.getElementsByTagName('div');
for(var i=0;i<myEl.length;i++){
myEl[i].myAtt=i;//a faux attribute
myEl[i].onclick=function(){alert(this.myAtt)}
}


So far so good. I wanted to extend this ideea upon Objects (in JSON), but it looks like the trick woun't make it:



var funcObj={
'onclick':document,
'onkeypress':document,
'onkeydown':document
}
for(ev in funcObj){
funcObj[ev].myAtt=ev;
funcObj[ev][ev]=function(){alert(this.myAtt)}
}

Where the error in my judgment? (I know objects are unordored collection, do not tell me that)

jkd
05-01-2006, 09:01 PM
funcObj[ev] references the document object for each ev in funcObj. Thus, you are assigning document.myAtt = ev during each iteration in the loop, leaving the value at the last one that occurs in the loop. You then assign document.[b]eventname[/n] = function() { alert(this.myAtt) }
So it will simply alert the last value assigned to myAtt, which explains why clicking generates an alert saying "onkeydown".

Kor
05-01-2006, 09:12 PM
Well I saw that, so maybe I should reformulate. Is it possible to attach a 'faux' attribute to an event? After all an event may be treatead like an object as well... Or the whole conecpt is an endless way?

vwphillips
05-01-2006, 10:40 PM
hmm


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<title></title>
<script language="JavaScript" type="text/javascript">
<!--
var funcObj={
'onclick':document,
'onkeypress':document,
'onkeydown':document
}
var Evt=0;
for(ev in funcObj){
funcObj[ev][ev+'T']=ev;
funcObj[ev][ev]=function(event){ if (!event) var event=window.event;
alert(this['on'+event.type+'T'])}
}

//-->
</script>

</head>

<body>

</body>

</html>

liorean
05-02-2006, 12:30 AM
Personally, I'd probably skip that property and use a closure instead. Here's a couple of possible solutions to your problem though. (Untested as usual...)
var
ev,
funcObj={
'onclick':document,
'onkeypress':document,
'onkeydown':document};

for(ev in funcObj){
solution0:
funcObj[ev][ev]=function(youreventdata){
return function(e){
if(!e)
e=window.event;
alert(youreventdata);};}(ev);

solution1:
funcObj[ev][ev]=function fn(e){
if(!e)
e=window.event;
alert(fn.youreventdata);};
funcObj[ev][ev].youreventdata=ev;

solution2:
funcObj[ev][ev]=function(e){
if(!e)
e=window.event;
alert(arguments.callee.youreventdata);};
funcObj[ev][ev].youreventdata=ev;
}

Kor
05-02-2006, 07:12 AM
Yes, thank you all. I knew that I could have used event/window.event. I was just curious if there could be another way to "catch" the name of the event on treating it same as a simple JSON object, not like a special event Object. It looks like there is no such a way.

Thank you all.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum