phil
phil

Reputation: 201

AS3 - Dispatch an Event DOWN the display list (instead of up)

Consider this (psuedo-code):

var country = new Country();
addChild(country);

var state = new State();
country.addChild(state);

var city = new City();
state.addChild(city);

I can dispatch events from the city up to the country like this (in the City class):

dispatchEvent(new CustomEvent(CustomEvent.WHATEVER));

Because events bubble UP the display list. But how can I dispatch an event from the COUNTRY class so that the City will hear it? When I add event listeners to the city, events dispatch from country do not register.

Upvotes: 1

Views: 548

Answers (3)

phil
phil

Reputation: 201

Probably not ideal, but I just added the listener to the stage from within the child object, so it catches the event when it bubbles up to the stage.

Upvotes: 1

bhups
bhups

Reputation: 14885

You can use singleton eventdispatcher class which might come very much handy in this case.

Upvotes: 0

Pranav Negandhi
Pranav Negandhi

Reputation: 1624

You could set up a city as a listener by referring to its parent's parent.

class City extends Sprite
{
    public function City()
    {
        this.addEventListener(Events.ADDED_TO_STAGE, this.foo()); // P.S. Verify event type. This is over the top of my head.
    }

    private function addedToStage(e:Event):void
    {
        this.parent.parent.addEventListener(Country.EVENT_TYPE, this.foo());
    }

    private function foo(e:Event):void
    {
        // Handle event
    }
}

Now all this is dandy, but there probably is a better way to architect your code. Right now, you have a circular dependency which can cause memory leaks if not cleaned up properly. If you can elaborate on your requirements, somebody might be able to suggest an alternative approach.

Upvotes: 0

Related Questions