AS3 Custom Event best practices

I’m just curious how a lot of you handle custom events.

My custom event/s that I will be creating pertain to creating and displaying views. I want to have two separate events dispatched, one to create the view and then one to display the view.

I see three ways of doing this:

  1. Create a single ViewEvent class with two constants CREATE_VIEW and DISPLAY_VIEW. The problem with a single event class is that I would like if possible to use strongly typed parameters. WHen using CREATE_VIEW though, I want to pass an ID that corresponds to the view to create and when I dispatch DISPLAY_VIEW I’d like to pass the view object to display. So I would need to either use two optional parameters, one for viewId of type int and one for view of type DisplayObject and then test for which one exists which I don’t like.

  2. Same as number 1 except use a single generic parameter and check for it’s type to see what the event’s payload is which I don’t like generic parameters either.

  3. Create two separate event classes, a CreateViewEvent and a DisplayViewEvent. This would allow me to use the proper typed parameters, but it seems a little weird since both event actions are so closely related that I feel they should be within the same event class.

So the question is… in general what are everyone’s views on handling a situation like this?

Hey kamcknig

I don’t know the exact purpose with why you have 2 separate events, but personally I would go with option 1. I definitely would not pass a generic argument as in option 2.

My decision is based on the purpose of the class, which in this case is to manage all the view events: Creating, displaying, removing, updating, sorting, etc.

Do both CREATE_VIEW and DISPLAY_VIEW events occur simultaneously? Have you considered doing it sequentially instead? So after you pass the viewId and the view is created, only then pass the DisplayObject?

With option 1, presumably you’d have a separate handler for each event and would therefore know which event you are handling. Thus you wouldn’t need to check if the property exists. For example:

function handleCreateView(e:ViewEvent):void { trace(e.viewID) }
function handleDisplayView(e:ViewEvent):void {trace(e.view) }