views:

162

answers:

2

ActionScript 3 / Flex 3 - Adding custom events to a class

Say I have the following Event:

import flash.events.Event;
public class SomeEvent extends Event
{
    public static const EVENT_ACTION:String = "eventAction";

    public function SomeEvent(type:String) {
        super(type);
    }

    override public function clone():Event {
        return new SomeEvent(this.type);
    }
}

... and the following Class:

public class SomeClass extends EventDispatcher
{
    public function someFunction():void
    {
        dispatchEvent(new SomeEvent("eventAction"));
    }
}

What is the best way to show that 'SomeClass' throws 'SomeEvent'? The only way I have found is to decorate 'SomeClass' with the [Event] attribute, as follows:

[Event (name="eventAction", type="SomeEvent")]

This allows me to instantiate the class and add an event listener by doing this:

var someClassInstance:SomeClass = new SomeClass();
someClassInstance.addEventListener(SomeEvent.EVENT_ACTION, mycallbackmethod);

Is there a better way to do this? Putting the [Event] attribute on the class followed by some string literals just feels ... wrong. Thanks in advance for the help!

A: 

I know, I feel the same way; using the string literals does seem a bit wrong somehow. But to the best of my knowledge, from all the documentation I've seen and the talks I've attended and in reading the Flex source code, etc., it does appear that's the proper way to do it.

Christian Nunciato
+3  A: 

You're doing it right. Currently, the AS3 compiler allows only string literals in metadata. Constants cannot be used.

By the way, Adobe's public bug database has a feature request to allow ActionScript constants in metadata. Feel free to vote for it.

joshtynjala