views:

160

answers:

3

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.

A: 

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.

Pranav Negandhi
Well, it could be more than 2 levels deep, so I don't want to go down the parent.parent road. There must be a better way for objects "down" the display list to listen for events?
phil
You seem to be building some kind of hierarchy here. In such a case, you should have a regular messaging pattern rather than have arbitrary nodes set up listeners to their parents. Look up implementations of tree views to understand what I mean.If you do go that route, then you should have the Country node store references to its child nodes in a list, then walk through the list whenever an event has to be triggered. The child node will similarly have a list of its own child nodes and pass on the message to each one.This approach removes circular dependencies and is easier to maintain.
Pranav Negandhi
A: 

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

bhups
A: 

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.

phil