Monday, February 13, 2012

Best Way to Write a Custom Event

Well, we all have written a custom event then what is the need of this post? Actually its true that writing a custom event is not a big deal but following up the best practices while writing definitely is!!

So no more jargon and lets start with the practices we need to follow:

  1. A Proper name should be assigned to the Event class. You may like to assign the name 'MyEvent' but just think how beneficial would that be to the developer who would be replacing you in future (if any). Moreover as we are writing an action-script class we should follow up all the best practices associated with that. For example our event class name should not be like: my-event, myEvent, my.event, my@event etc.
  2. Sometimes (rather most of the times) we need to also pass some variable along with the custom event. Then developers generally create some param variables of Object type and then set them and pass along with the event. Well there are two things to observe (and follow) here:
    1. First of all we should try to provide exact type so that problem of type checking does not happen and it will also improve memory aspect.
    2. We should always try to make them private because as per the best practice these variables should not be altered during the course of event movement. Sometimes we catch an event at one place and try to modify its properties and then again dispatch. That is a bad practice!!
  3. We can declare all the event types as static string constants in the class itself as it reduces the chances of spelling error with event name as well as helps in managing all the event constants at one place.
  4. We should also override clone() method because if we don't override this method we will get a new instance of normal event (and not of our custom event) if we re-dispatch our custom event. This is not what we desire because normal event will not have all the properties we have stated (for example we may have changed bubbling behavior as well). read about clone here.
  5. We should also provide toString() implementation for our custom event.
  6. Finally it is always good to provide some AS Doc to the event constants and class as well.
There are plenty of good examples of custom event in flex and all good examples generally follow all these guidelines. But I thought these simple guidelines may be helpful for people not having much experience in this field. read more.


FlexProg said...

Good advice :)

Akhil said...

Thanks FlexProg.

Anonymous said...

Can you give some example code please??

ADmin said...

It is adequate if your article arrangement is unpleasant or ambiguous as of right now, or in the event that you don't have an awesome bargain of portion.