views:

609

answers:

4

So, events bubble up the display list. That's great if that's what you want. But what if you have objects on the stage that are not related that need to listen for events from each other? A simplified example:

var objA = new ObjA;
addChild(objA);

var objB = new ObjB;
addChild(objB);

var objC = new ObjC;
objB.addChild(objC);

Object B can listen for events dispatched by object C. But I also need object A to listen for events dispatched by object C. Also, these objects are created in different classes so I can't hard code references to each other. Solution?

A: 
bhups
Interesting solution. Would explore this if my object couldn't access the stage.
phil
A: 

solution: If your events are properly bubbling, you should be able to set a listener on the stage from any class that extends DisplayObject and is on a display chain.

catch: If you just listen for the standard events you are not going to really be able to tell where they are coming from unless you know that a particular event can only be coming from one "place".

fix: In cases like this it's best to dispatch custom events.


inside any class that extends DisplayObject

stage.addEventListener(MyAwesomeEvent.SOMETHING_SUPER_SWEET, sweetHandler)
greg
This works, thanks.
phil
A: 

Thank You SOOOOOOOOOOOOOOOOOOO MUCH!

is there any problem with memory leaks when adding a lot of events this way? could be a good practice to remove listeners after use? if so, how to do it with this singleton class?

Thanks!

Victor
A: 

there's no need to remove your listeners, if you use the last parameter of addEventListener(), which should be set to true it means that your listener will use weak reference, and thus will not prevent GC from collecting the owner of the listener.

poco