0
votes

I hvae an array called ary and some objects in this array,which is ary[0],ary[1],ary[2],ary[3] and ary[4].There is a text property in every element.I want to add an eventListener for all elements in ary and pass the property to a function.At first,I do it as below:

    ary[0].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[0].topname.text)});
    ary[1].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[1].topname.text)});
    ary[2].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[2].topname.text)});
    ary[3].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[3].topname.text)});
    ary[4].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[4].topname.text)});

function toGo(e:MouseEvent,str:String){
   ......
}

it does work.But when I change it in for(...){...},it has an error.

for(var i=0;i<arylength;i++){ ary[i].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[i].topname.text)}); }

for above code,I got an error "TypeError: Error #1010: A term is undefined and has no properties.".Then I also try another way.

for(var i=0;i<ary.length;i++){ namestr=ary[i].topname.text; ary[i].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,namestr)}); }

It has no error,but the variable "namestr" I get is always the variable of the last element in ary. Why?

Where did I make the mistake?

Thanks.

1

1 Answers

1
votes

Your first for loop, the error is a missing period between ary and length. You have arylength but it should be ary.length.

A better way to do this would be the following: (not using annonymous functions, use the event's currentTarget property to figure out which item was clicked)

for(var i=0; i < ary.length; i++){
    ary[i].addEventListener(MouseEvent.CLICK,itemClick,false,0,true);
}   

function itemClick(e:Event):void {
    toGo(e, Object(e.currentTarget).topname.text;
    //replace the object cast with whatever type your ary items are
}

//or even better, just go right to the toGo function and figure out the item clicked there.