redconservatory
redconservatory

Reputation: 21924

dispatching from an object not in the display list?

I have an object that controls another object that is on the display list.

The setup looks like this:

Parent (Main Timeline)
- Child 
-- Grandchild --> contains instance of behaviour class that controls the grandchild's movement

I have an event in the "behaviour" that I'd like to reach the parent, but the behavior does not extend Sprite or MovieClip.

How can I get this event to reach the parent?

Upvotes: 0

Views: 371

Answers (2)

cwallenpoole
cwallenpoole

Reputation: 82028

There are two ways. If the "behavior" object has access to the GrandChild, the GrandChild has a root property (which, conveniently) is the root -- this will only work if there is a path-to-root though. You can't remove a child (or its parents) and then expect to be able to access the root directly. But, if you have a DisplayObject which you know is on the stage, you can use that to communicate to the root directly. (You can also, with proper casting, access all of the parents and grandparents of the Grandchild).

You can also have a centralized EventDispatcher which is listened to by whatever you want to listen to it. Basically, create a Singleton (you'll need to look that up for the AS3 way) which subclasses EventDispatcher and then tell that to dispatch whatever events you need.

It would look something like this:

//on the root
EventDispatcher.getInstance().addEventListener( "myCustomEvent", myEventhandler );

//in behavior
EventDispatcher.getInstance().dispatchEvent( new Event( "myCustomEvent" ) );

//root now acts accordingly.

Upvotes: 2

DTRx
DTRx

Reputation: 251

The "BubblingEventDispatcher" class you are referring to is a bit misleading. It's actually just adding children to the display list in order to enable bubbling:

AS3 Event Bubbling outside of the Scenegraph/DisplayList

In order to relay events without having access to bubbling, you are basically stuck listening for the events on every level and relaying them along manually. It accomplishes the same thing as if you had bubbled the event but it's more of a hassle and it also introduces tighter coupling.

Upvotes: 1

Related Questions