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:
var e:ContactEvent = new ContactEvent(contact, "contractSaved")
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 class ContactEvent extends Event {
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:
var e:ContactEvent = new ContactEvent(contact, ContactEvent.CONTACT_SAVED);
No more mystery event names!
1 comments - Posted by Joe Rinehart at 10:01 AM - Categories: Flex | Best Practices