views:

1308

answers:

4

So, In a Flex app I add a new GUI component by creating it and calling parent.addChild(). However in some cases, this causes an error in the bowels of Flex. Turns out, addChild actually does:

return addChildAt(child, numChildren);

In the cases where it breaks, somehow the numChildren is off by one. Leading to this error:

RangeError: Error #2006: The supplied index is out of bounds. at flash.display::DisplayObjectContainer/addChildAt() at mx.core::Container/addChildAt() at mx.core::Container/addChild() . . at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at mx.core::UIComponent/dispatchEvent() at mx.controls::SWFLoader::contentLoaderInfo_completeEventHandler()

Is this a bug in Flex or in how I am using it? It kind of looks like it could be a threading bug, but since Flex doesn't support threads that is a bit confusing.

A: 

I have noticed that it most often occurs when re-parenting a UIComponent that is already on the display list. Are you re-parenting in this situation?

Have to check. Any idea how to fix it though?
MidnightGun
+1  A: 

Could it be possible that you are adding a child before the component has been full initialized? Maybe try adding a child after Event.COMPLETE has been broadcast?

It may not support threads but it's still asynchronous...

onekidney
If I remember correctly, I had this same problem and this was the culprit.
hasseg
A: 

OK, like a dope, I was trying to add a child to a container even though it was already there, hence the confusing "wrong insertion index" message.

A: 

numChildren doesn't validly reference an existing index in the children array. Arrays in AS3 are indexed starting at 0. This means that the last item in your array as for index numChildren - 1, not numChildren.

try addChildAt(child, numChildren - 1);