membersound
membersound

Reputation: 86627

How to dispatch an event with dynamic content in Flex?

I often have the requirement to dispatch a flash.events.Event with soem custom String text, like:

protected function mouseClicked(event:Event) {
     //here I'd want to notify anyone interested in the button click,
     //and also transfer the name of the button (or whatever) that was clicked - assume some dynamic value
     dispatchEvent(new Event("myMouseEvent"), button.name));
}

Of course the above event is invalid. But is there any event that can be used for that type of events? Maybe the TextEvent, but I don't know if I'd be misusing it here.

Upvotes: 1

Views: 289

Answers (1)

Aaron Beall
Aaron Beall

Reputation: 52133

To include additional data with your events, create a custom event class by extending Event (or any sub-class of Event) and adding your own properties. For example:

class NameEvent extends Event {
    public static const NAME_CLICK:String = "nameClick";
    public var name:String;
    public function NameEvent(type:String, name:String) {
        this.name = name;
        super(type);
    }
}

dispatchEvent(new NameEvent(NameEvent.NAME_CLICK, button.name));

Note that your event type strings ("nameClick" in this example) should be globally unique, otherwise listeners could get them confused with other event types. For example "click" is already expected to be a MouseEvent. I often add prefixes to my custom event types, for example "NameEvent::click".


Another option that does not require creating a custom event is to rely on the expected target to get additional data. For example:

// dispatch a custom event from a Button
dispatchEvent(new Event("myClick"));

// handler for "myClick" events on the button
function myClicked(e:Event):void {
    var button:Button = e.target as Button;
    trace(button.name);
}

This is not as flexible and also more fragile than using a custom event class, but sometimes a quick easy solution.

Upvotes: 2

Related Questions