0

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 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry for "arylength",it's just my typo. I use your way to correct my code,then it really does work. Thank you very much.Except for one line function itemClick(e:Event):void {,it should be function itemClick(e:MouseEvent):void {.
MouseEvent extends Event, so either is fine, unless you actually want to use any properties specific to MouseEvent then yes, you'll want it to be mouse event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.