views:

30

answers:

3

I want to have a main logic class that listens for dispatched events from an assortment of other classes.

for instance:

i have a parent Map class that contains X instances of a State class. When the user clicks on a State class, i want to dispatch an event CLICKED along with the name of the state.

now this Logic class will see this new event and process the name of the state and perform some other logic stuff... etc.

no matter what i try i can only get it to work where the State class listens for its own Dispatched event. Which to me seems a waste, i could have just manually called the function.

I have read so many tutorials online about custom events/ dispatching and they are being used in a basic one class example.

A: 

use singleton EventDispatcher approach.

package 
{
  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 {}
Now in you State classes you can call:
SingletonDispatcher.GetInstance().dispatchEvent(new StateEvent(...));
And in you main Login class you can listen like this:
SingletonDispatcher.GetInstance().addEventListener(StateEvent.SOME_EVENT, onstateEvent);

bhups
A: 

If the parent Map class contains many State class instances , you could create your Logic class in the parent class and pass it in the constructor of your State class as an event dispatcher. For this example, I assume that you will create a LogicEvent , with a stateName property. Here's a simplified code version:

public class Map extends Sprite
{
    private var logic:Logic = new Logic();

    public function Map()
    {

       //when you create your state instances
       var state:State = new State(logic);
    }
}

public class Logic extends EventDispatcher
{
    public function Logic()
    {
       this.addEventListener(LogicEvent.STATE , logicEventListener );
    }

    private function logicEventListener(event:LogicEvent ):void
    {
       trace( event.stateName );
    }
}

public class State extends Sprite
{
    private var dispatcher:EventDispatcher;

    public function State(dispatcher:EventDispatcher)
    {
        this.dispatcher = dispatcher;
     }

    private function clickHandler(event:MouseEvent ):void
    {
       dispatcher.dispatchEvent(new LogicEvent(this.name) );
    }
}
PatrickS
A: 

Robotlegs framework would be a good solution for this. It provides a simple way for loosely coupled objects to receive events on a shared event dispatcher.

Stray