0

I need an event redispatcher at the top of the DisplayObject hierarchy.

Simple situation built from other questions of mine:

public class Main extends MovieClip { // Document Class at Flash
    private var objectA:ClassA;
    private var objectB:ClassB;

    public function Main() {
        objectA = new ClassA();
        addChild(objectA);
        objectB = new ClassB();
        addChild(objectB);
    }
}

 

public class ClassA extends Sprite {
    public function ClassA() {
        addChild(new Bitmap(new BitmapData(20, 20, false, 0))); // A black square
        addEventListener(MouseEvent.CLICK, clickedA);
    }

    public function clickedA(evt:MouseEvent):void {
        dispatchEvent(new TextEvent("myEventType", true, false, "success"));
    }
}

 

public class ClassB extends Sprite {
    public function ClassB() {
        addEventListener("myEventType", myFunction);
    }

    public function myFunction(evt:TextEvent):void {
        trace(evt.text);
        var color:uint = evt.text == "success" ? 0x00FF00 : 0xFF0000;
        addChild(new Bitmap(new BitmapData(20, 20, false, color)));
    }
}

myFunction should react to the dispatch through Main.

What do I have to implement on Main to make it serve as a relay for dispatched events from a child to its other children?

Consider it can have many children as dispatchers and receivers/listeners. In other words, it has to be generic so I won't have to implement one relay for every case.

Community
  • 1
  • 1

3 Answers3

0

in ClassB you should addEventListener to the main, for example if var main is a reference to the main class,

main.addEventListener("myEventType", myFunction);

would be a good solution.

csomakk
  • 5,369
  • 1
  • 29
  • 34
0

You really don't want to patch all your events through Main, you just want to patch them through something. A term for that something is an event bus.

There are some standalone event bus implementations out there (e.g., as3commons-event-bus), or you can move towards a full MVC framework (e.g. RobotLegs, PureMVC).

People differ in opinion about whether using event buses is a good thing. It's handy for decoupled communication (pro), but it's usually a big singleton everyone subscribes to (con).

Michael Brewer-Davis
  • 14,018
  • 5
  • 37
  • 49
0

Solution #1:

Main:

objectB = new ClassB();
objectA = new ClassA(objectB);

ClassA:

objectB.myFunction("success");

ClassB:

public function myFunction(text:String):void {/*...*/}

Solution #2:

Main:

public var objectB:ClassB;
//objectB.name = "b";

ClassA:

var main = root;
//var main = stage.getChildAt(0);
//var main = stage.getChildByName("root1");

Main(main).objectB.myFunction("success");
//ClassB(Main(main).getChildByName("b")).myFunction("success");

ClassB:

public function myFunction(text:String):void {/*...*/}
  • Thank you! **Solution #2:** `Main(root).objectB.myFunction("success");` is everything I needed. –  Dec 27 '12 at 06:02