2 Replies Latest reply on Dec 9, 2007 1:46 PM by Monkey_House

    addEventListener Best Practice

    Monkey_House
      Most of the examples I have found related to event listening has been an application listening for an event triggered by a component. What I want is a component to listen for an event triggered from anywhere.

      I've been able to get it to listen for an event called from parent component but considering how often loose coupling is discussed I feel there has to be a better way.

      For example, my parent component calls:
      dispatchEvent(new Event("someEvent", true));

      and the component called from within the parent listens for the event:

      private function init():void{
      parent.addEventListener("someEvent",doIt);
      }

      This works but the component listening assumes the event will be called from its direct parent. If I want the same event or another to be possibly triggered from its parent's parent I would have to do parent.parent.addEventListener

      There has to be a better way. How do you handle events that should cascade down to the most basic components?

        • 1. Re: addEventListener Best Practice
          peterent Level 2
          Desigining a framework with general broadcast events would take more processing power than it would be worth - plus a lot more complication.

          An easier thing for you to do is create a class which can register event listeners and dispatch the events to those listeners. Here's something using your example.

          public class EventWarehouse extends EventDispatcher {
          public static function getInstance() : EventWarehouse {
          if( self == null ) self = new EventWarehouse();
          return self;
          }
          private var self:EventWarehouse;
          }
          }

          From your child component:
          EventWarehouse.getInstance().addEventListener( "someEvent", doIt );

          From your parent:
          EventWarehouse.dispatchEvent( new Event("someEvent") ) ;

          You can probably come up with something a bit more elegant than this, but it might be something you can use.
          • 2. Re: addEventListener Best Practice
            Monkey_House Level 1
            Thanks. I'll give it a try.