Search code examples
actionscript-3event-handlingaddeventlistenerdispatchevent

How far can one event go and how do I listen for it?


I have code in a flex component that I want to listen for an event, the source of the event is a custom class that's being run by another class that's being run by another class etc etc. I was under the impression that an event would pass throughout the whole application, so I was hoping if I dispatched the custom event in the class like so..

    private function finishEvent():void {
        var evt:EventDispatcher = new EventDispatcher;
        var finished:Event = new Event("finishedInterpret");
        evt.dispatchEvent(finished);
    }

then I could just grab it in my component like this:

public function interpret(data:Array):void {
    addEventListener("finishedInterpret", applyInferences);
    db.executeBatch();
}

the event gets fired basically when the executeBatch is finished, and the finishEvent is being called, but I'm the listener isn't getting anything. I tried setting it to db.addEventListener, but that had now effect.


Solution

  • The way that events are supposed to happen is that an object dispatches events, and consumers of those events listen for events from that object. Unless you have a global event dispatcher (not typical), there is no application-wide event dispatching.

    I find this to be the best pattern to use: child components dispatch events, and the owner of those children listen for their events. For example:

    child.addEventListener("finishedInterpret", applyInferences);
    

    As is, your code is listening for events from itself.