Properly naming custom Flex events
Posted by Joe Rinehart at 10:01 AM
1 comments - Categories:
Flex | Best Practices
A Flex developer asked me a question about events today. "[When using events], Flex code hinting does something like customName.CUSTOM_NAME. Any idea where it's getting that from?"
When you're creating your own events, it's important to follow this convention: it enables greater compile-time checking of event types.
Let's pretend I was working with Contacts, and I created a ContactEvent with types of "contactSaved" and "contactDeleted" being used in MXML components.
In my component, I do this to create a contact event:
Whoops, I just typed "contractSaved" as the type. That's going to make me spend forever figuring out why its listeners aren't being fired.
To save this kind of mess, use static constants on your custom events and avoid the "magic string" antipattern:
public static const CONTACT_SAVED:String = "contactSaved";
public static const CONTACT_DELETED:String = "contactDeleted";
// other code }
Now, when you raise the event, reference the constant:
No more mystery event names!
Axel wrote on 09/19/07 10:26 AM
BEAUTIFUL... never thought about doing this, but i ran into a problem yesterday with a mistyped event name that wasted 15 or 20 min of my time (thats only because i caught it early), and this is a great solution... what a coincidence on timing of your blog post and my small issue... gooooooood stuff joe.