How to access object defined in parent, from child Slider movieclip

user2981 picture user2981 · Oct 10, 2012 · Viewed 18.9k times · Source

Here is my app structure:

parent->[slider->[movieClip1,movieClip2,movieClip3]]

So I basically have a few movieclips inside a Slider component.
Now I have an object defined in the parent time line

var myObj:Object = new Object();... 

I want to access this object from movieClip1 in the Slider component.
I've tried:

trace(MovieClip(this.parent).myObj.A_function_in_the_object());

Which outputs:

TypeError: Error #1034: Type Coercion failed: cannot convert fl.controls::BaseButton@222082e1 to flash.display.MovieClip. at SliderTrack_skin/frame1()

And

trace(parent.myObj.A_function_in_the_object());

Which outputs:

1119: Access of possibly undefined property myObj through a reference with static type flash.display:DisplayObjectContainer.

How do I access the object that's defined in the parent timeline from a child movieclip?

Answer

Yasuyuki  Uno picture Yasuyuki Uno · Aug 25, 2015

Because the structure of flash components are complex, this.parent doesn't always return the class that you expected. So, if you want to access parent object, you should use while loop instead of "this.parent.parent.parent ... ".

Like this.

var obj: Object = this;
while (obj.parent != null) {

    obj = obj.parent;

    // If "obj" is the class you expected, stop loop.
    if (obj is MovieClip) {

        // Do something like below.
        MovieClip(obj).myObj.A_function_in_the_object();
        break;
    }
}