Using AsBroadcaster to Broadcast Custom Messages

 <  Day Day Up  >  

Using AsBroadcaster to Broadcast Custom Messages

As was mentioned, we are not limited to listening to built-in objects. Flash MX 2004 has a static class that we can use to allow any Flash object to have listeners subscribe to it. This class is named AsBroadcaster .

N OTE

At the time this book was published, AsBroadcaster was an undocumented feature of Flash MX 2004. It should be used cautiously; there is no guarantee that it will be implemented in future versions of Flash.


AsBroadcaster essentially has a single method, initialize . This method takes an object as an argument. It returns that object, with three new methods added to it. These new methods are addListener , removeListener , and broadcastMessage . The first two methods act just like the methods of the same names discussed earlier in the chapter. The third method added with AsBroadcaster and broadcastMessage enables an object to send a message that will be captured by any objects listening to it. Listing 7.6 shows an object being created and initialized as a broadcaster .

Listing 7.6. Initializing an Object as a Broadcaster
 var myBroadcastingObject:Object=new Object(); AsBroadcaster.initialize(myBroadcastingObject); 

After an object has been passed to the initialize method of AsBroadcaster , the three methods are automatically associated with it. This can be verified by running this trace statement:

 trace(myBroadcastingObject.addListener); 

When run, the code will output [type Function] , confirming that addListener is now a method of myBroadcastingObject .

Let's consider a slightly more complicated example within the framework of an object-oriented application. Figure 7.4 shows the Stage for our example. On the Stage, there are four visual elements all contained within a single movie clip. The movie clip has a symbol name mcBroadcast in the Library, and it has an instance name of broadcast_mc . In the Linkage panel for the mcBroadcast clip, this clip is set to be exported for ActionScript, and it is set to implement the ActionScript 2.0 class BroadcastView .

Figure 7.4. This movie, with a circle, square, text field, and combo box, serves as the framework to demonstrate AsBroadcaster .

graphics/07fig04.gif

Listing 7.7 shows the source code for BroadcastView.as. In the listing, all the code associated with the application is located in the class file; the code is neither on a frame of the timeline nor directly on the MovieClip object itself.

T ip

In Flash MX 2004, the use of suffixes such as "_mc" are no longer necessary to enable code hinting. However, as applications grow in complexity, it is always a good idea to have a naming convention in place to help developers quickly identify the types of any object by glancing at the name. There is no right or wrong naming convention, but we strongly recommend the use of a consistent naming convention throughout an application.


Listing 7.7. BroadcastView Defines the Behaviors for Our Movie Clip
 class BroadcastView extends MovieClip{       // declare visual objects       var combo:mx.controls.ComboBox;       var rec_mc:MovieClip;       var oval_mc:MovieClip;       var text_mc:MovieClip;       // declare properties of class       var colorsArray:Array;       var addListener:Function;       var value:Number;       // constructor       public function BroadcastView (){             colorsArray = this.buildArray();       }       function onEnterFrame(){             this.postInit();       }       function postInit(){             this.fillComboBox(this.colorsArray);             this.combo.addEventListener("change",this.changeColor);             AsBroadcaster.initialize(this);             this.addListener(oval_mc);             this.addListener(rec_mc);             this.addListener(text_mc);             this.onEnterFrame = null;       }       private function buildArray():Array{             var theArray:Array= new Array();             theArray.push(new TheColor("Red",0xff0000));             theArray.push(new TheColor("Blue",0x0000ff));             theArray.push(new TheColor("Green",0x00ff00));             theArray.push(new TheColor("Yellow",0xffff00));             theArray.push(new TheColor("Pink",0xff00ff));             theArray.push(new TheColor("Cyan",0x00ffff));             return theArray;       }       private function fillComboBox(colorsArray){             for(var i:Number=0;i<colorsArray.length;i++){                   this.combo.addItem(                         colorsArray[i].colorName,                         colorsArray[i].hexColor                   );             }       }       public function changeColor(){             this._parent.broadcastMessage("changeColor",this.value);       } } 

Listing 7.7 begins by declaring properties for the class. The first four properties represent the visual instances already on the Stage ”three movie clips and a combo box. Next , colorsArray is defined as an array. The properties value and addListener are also defined; value represents the data associated with a selected item in the ComboBox component, and addListener represents the new methods that become available to the class by initializing it with AsBroadcaster . In reality, the only reason these need to be defined here is to escape compile-time errors. Writing this class file without those two definitions would cause Flash to throw an error because there is neither a property named value nor a function named addListener .

The class's constructor populates the colorsArray property using the buildArray() method ( buildArray will be discussed shortly). Next, we define an onEnterFrame method. This method is actually a system event handler of the MovieClip class, which is invoked at the frame rate of the movie. It's being used here to enable a method to be invoked a few milliseconds after the rest of the clip has loaded.

The method we call next is named postInit . The postInit method works with the visual objects on the Stage. Due to synchronicity issues, it's necessary to wait until all the elements are drawn on the Stage before working with properties or methods of visual objects. Using the onEnterFrame event to invoke postInit enables the postInit method to be invoked 83 milliseconds after the stage is completely rendered (83 milliseconds is approximately 1/12 of a second, and the default frame rate is set at 12 frames per second). These 83 milliseconds are enough time for the synchronicity issues to be bypassed. Within postInit , the combo box is filled using the fillComboBox method.

Next, the changeColor method is assigned as the event handler for the change event of the combo box. This is done by using the addEventListener method discussed earlier. Then, we use AsBroadcaster to assign the movie clips on the Stage ( oval_mc , rec_mc , and text_mc ) as listeners to this class. Last, the onEnterFrame method is erased by setting it equal to null . This is done so that the method is called only once, shortly after initialization.

The buildArray method is defined next. It creates a new array and populates six elements as instances of the TheColor class. It then returns the array. Listing 7.8 shows the class definition of TheColor .

Next, the fillComboBox method is defined. It accepts an array of colors as an argument and uses the array to populate the combo box. The color 's colorName property is used as the label, and its hexColor property is used as the underlying data.

Last, the changeColor method is defined. This is the method that is invoked when the value of the combo box is changed. The changeColor() method has a single line of code, which broadcasts the message changeColor and passes the value of the currently selected item in the combo box. Shortly, we will see how each of the listening movie clips will have a unique response to this one message.

N OTE

Notice that the changeColor method uses this._parent as the scope when it invokes the broadcastMessage method. It does this because a function or method acting as an event handler for a component is invoked within the scope of the component rather than the scope of the class, as was mentioned in a Tip earlier this chapter. This method broadcasts the selected color to all the listening objects.


Listing 7.8. The Class File for TheColor Defines How Instances of TheColor Are Built
 class TheColor{       var colorName:String;       var hexColor:Number;       function TheColor(name,hex){             this.setName(name);             this.setHex(hex);       }       private function setName(name:String):Void{             this.colorName = name;       }       private function setHex(hex:Number):Void{             this.hexColor = hex;       }       public function getName():String{       return this.colorName;       }       public function getHex():Number{             return this.hexColor;       } } 

This class is very simple. It has two properties, colorName and hexColor . The constructor sets the properties based on the values passed to it. A series of getter and setter functions complete the class. Instances of this class are used within the combo box to enable users to see the name of a color; the color's hexadecimal value will be available as the data.

The other visual objects on the Stage each have class files associated with them. These other classes simply define a changeColor method for the class, allowing them to respond to the changeColor message being broadcast.

Both mcOval and mcRec (the Library items associated with oval_mc and rec_mc ) are defined through the Linkage panel as implementing the ActionScript 2.0 class ColorChanger . Listing 7.9 shows the implementation of the ColorChanger class.

Listing 7.9. The ColorChanger Class Has a Single Method That Fires When the changeColor Message Is Broadcast to It
 class ColorChanger extends MovieClip{       function changeColor(color:Number):Void{             var newColor = new Color(this);             newColor.setRGB(color);             delete newColor;       } } 

The one method here accepts a numeric value, color . Next, it creates a new instance of the Color class, which will operate on it. The Color instance's setRGB method is used to assign the color to the instance. Last, the color instance is deleted because it is useful only until its setRGB method is invoked.

The mcText symbol (the Library item associated with text_mc ) is defined through the Linkage panel as implementing the ActionScript 2.0 class TextMovie . Listing 7.10 shows the class definition for TextMovie .

Listing 7.10. TextMovie Has a Single Method ” changeColor ”That Fires When the changeColor Message Is Broadcast to It
 class TextMovie extends MovieClip{       var dynTxt:TextField;       public function changeColor(color:Number):Void{             DynText.textColor=color;       } } 

This class is aware of a single text field ”with an instance name dynText ”on its Stage. The changeColor method accepts a numeric color value and uses that value to change the color of the text within the DynText field.

With this example, we can see how custom messages can be broadcast with the use of AsBroadcaster . A single message is broadcast to three separate objects, implementing two independent classes. Each class has its own individual method for handling the message. Figure 7.5 shows the application running.

Figure 7.5. When the application is run, the text and two shapes change color to match the color chosen from the combo box.

graphics/07fig05.gif

 <  Day Day Up  >  


Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net