开发者

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

开发者 https://www.devze.com 2022-12-14 13:23 出处:网络
Consider this (psuedo-code): var country = new Country(); addChild(country); var state = new State(); country.addChild(state);

Consider this (psuedo-code):

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

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

var city = n开发者_如何学运维ew 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.


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消