开发者

AS3 dispatch events to objects not related on the display list

开发者 https://www.devze.com 2022-12-11 14:10 出处:网络
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 event开发者_如何学Gos from each ot

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 event开发者_如何学Gos 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?


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)


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.


Then probably, you can make a Singleton EventDispatcher and use it in all classes to dispatch the event.

package <WHATEVER>
{
  import flash.events.*;
  public class SingletonDispatcher extends EventDispatcher {
    private static var dispatcher:SingletonDispatcher = null;
    public function SingletonDispatcher (enforcer:SingletonEnforcer) : void {
      if (!enforcer) {
       throw new Error("Direct instatiation is not allowed");
      }
      return;
    }// end function
    public static function GetInstance() : SingletonDispatcher {
      if (!dispatcher) {
        dispatcher= new SingletonDispatcher (new SingletonEnforcer());
      }// end if
      return dispatcher;
    }// end function
  }
}
class SingletonEnforcer {}

Then you can use in the all classes like:

public class C {
...
SingletonDispatcher.GetInstance().dispatchEvent(new SomeEvent()); // instead of this.dispatchEvent
...
}

And in class A, you can listen to it:

public class A {
  ...
  SingletonDispatcher.GetInstance().addEventListener(SomeEvent.UNREACHABLE_EVENT, thankGod);
  ...
}
0

精彩评论

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

关注公众号