Okay, this was hard for me to wrap my brain around, so let me summarize, in case anyone else is stuck on this. When developing in Flex, all the standard components let you specify a listener when you create them in MXML, like this:
<mx:Button id="someButton" click="handleClick( event );"/>Now when someone clicks on someButton, it calls the function handleClick(). Although not strictly best practice, it really is a nice little shorthand for adding an event listener to a Flex component. And since the Adobe components contain this functionality, people are used to it. If you have any plans of releasing your component into the wild, people will expect it to act like the components they already know and love.
Well, here’s how you do it: with the [Event] metadata tag.
1- First of all, the tag goes before the class declaration because it applies to the entire class. You can actually have more than one of these tags, for different events that you might broadcast. In my example, I have two, and they both broadcast ModelEvents.
// create the [Event] tags [Event(name="onLoad", type="com.pixelwelders.events.ModelEvent")] [Event(name="onLoadError", type="com.pixelwelders.events.ModelEvent")] // declare your class public class DataModel extends EventDispatcher implements IModel { ...
2- The type attribute refers to the actual type of event that this class broadcasts, package and all.
3- The name attribute refers to the string you use when you create a new Event of this type. You have to use an actual literal here; you can’t use a variable like ModelEvent.LOADED. So if you are dispatching an event like either of these:
dispatchEvent( new ModelEvent( ModelEvent.LOADED ) ); dispatchEvent( new ModelEvent( ModelEvent.LOAD_ERROR ) );
…you’ll need to check in your Event class to see what the actual value of LOADED or LOAD_ERROR is. In my ModelEvent class, I have:
public static const LOADED : String = "onLoad"; public static const LOAD_ERROR : String = "onLoadError";
Thus, my complete Event metadata tags are:
[Event(name="onLoad", type="com.pixelwelders.events.ModelEvent")] [Event(name="onLoadError", type="com.pixelwelders.events.ModelEvent")]
Of course, that’s only the first part of the equation. The second part is listening for the event, which thanks to our [Embed] tags, is now a piece of figurative cake. Here’s my Flex tag:
<model:DataModel
id="dataModel"
xmlURL="fileName.xml"
onLoad="handleModelLoaded( event );"
onLoadError=”handleModelError( event );”/>That onLoad and onLoadError attributes have the same value as your name attributes that you specified in step 3 above. Now put your two handlers in your Script tag, and they will be called any time those events are fired. Voilà.
Discussion
No comments for “Broadcasting Events from Custom MXML Components - The [Event] Tag”
Post a comment