Thursday, September 27, 2007

Flex Events: Introduction

Using events enables a loosely coupled architecture. To broadcast an event from a component you need to use the dispatchEvent method. This method is defined in the flash.events.EventDispatcher class. Observer pattern.

You need to declare the events that may be dispatched by a component. A component may dispatch any event declared by any of the superclasses

In Flex events can be declared using metadata tag [Event], which is used to declare the event publicly so that the MXML compiler recognizes it.
<mx:Metadata>
[Event(name="eventName",type="flash.events.Event")]
</mx:Metadata>
We can specify type. If not mentioned, default is flash.events.Event
The name used here is used to initialize the event type parameter before it is dispatched i.e.
var e:Event = new Event("eventName");

Now when this component is initialized, we can use the event name like any other attribute and specify a function to call
<m:CustomComponent id="myComp" eventName="someLocalFunction()"/>

Many times we may also need to pass around data with the events. Cannot be done with the basic flash.events.Event class. But we can create an event subclass. You will generally need to override clone method of the Event class

Summarizing, we will have these elements in event handling:
1. The event class: you can extend the Event class. clone method is overridden then and the data that we expect the event to carry is member var
2. Event dispatching component: Generally a UI component will dispatch the event after creating in at the appropriate function. The component declares all the events it can dispatch.
3. The listener/event target component/app: This is generally the parent/top level component that uses the event dispatching component. If it is interested in any event dispatched by it, it handle it by listening to it.

Questions
  1. Why should you use events?
  2. What design pattern does events mechanism employ?
  3. How will you declare an event?
  4. What is default event type?
  5. Why would you use a custom event?
  6. With a small example and code explain how events work in flex.

No comments: