Search code examples
apache-flexglobalevent

Event-based interaction between two custom classes


I have such problem: I have 2 custom components, which have their own nesting hierarchy ... One is container for another. I have to "familiarize them" with each other. The way I'm trying to achieve that is using global events (one side is firing and the other one is catching):

Application.application.addEventListener("Hello", function (data:Event):void{
        // .. some actions
    });

//and
Application.application.dispatchEvent(new Event(Hello));

Everything is pretty good, but there's one thingy .. when I'm trying to catch the event, I can't access the class, who is catching it. E.g.:

  1. Container fires the event.
  2. Child caughts it.
  3. Then should be created the connection between container and it's child.

BUT, the only thing I could acheive is passing a reference to the Container in the DynamicEvent. Is there any chance that I could access the child at the event-handler function. Or maybe there's more elegant way to solve this problem ...

Any help would be greately appreciated :)


Solution

  • In most cases, either target or currentTarget will give you access to the component that is firing the event.

    http://livedocs.adobe.com/flex/3/langref/flash/events/Event.html http://livedocs.adobe.com/flex/3/langref/flash/events/Event.html#currentTarget http://livedocs.adobe.com/flex/3/langref/flash/events/Event.html#target

    However, with your approach, you are firing the event from the top level application; not from either of your nested components. This strikes me as unusual.

    I envision you have a hierarchy like this:

    Application

    --- Container1

    -------Container2

    I would recommend firing the event from container2 and listening for it in container1.

    Your dispatch code in Container2 will be something like this:

    this.dispatchEvent(new Event('myCustomEvent'));
    

    In container1 you can listen for the event something like this:

    container2.addEventListener('myCustomEvent', onMyCustomEvent);
    

    If you do need to add custom event data to your event; you can create your own custom event class and add data. Do you have a specific use case for firing the events off the Application container? I'd love to hear it.