ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Example: Number Manipulator | 261

parameters, a slot position and command object (line 17), and assigns the command


to the requested slot position in thecommandListarray. ThesetButton( )method takes


two parameters, a slot position as before, and button text (line 22). ThesetButton( )


method creates a newTextButtoninstance, and assigns it to the requested location on


thebuttonListarray. It then draws the button, assigns an event handler to intercept


mouse clicks, and adds it to the display list. The mouse click is the trigger for the but-


ton and its assigned command object. When there’s a click on the button, the event is


intercepted by thebuttonClicked( )method, which traverses thebuttonListarray to


find the button clicked. And when the originating button is found, it executes the cor-


responding command object from thecommandList array.


Example 7-15. InvokerPanel.as


1 package
2 {
3 import flash.display.*;
4 import flash.events.*;
5
6 class InvokerPanel extends Sprite
7 {
8 var commandList:Array;
9 var buttonList:Array;
10
11 public function InvokerPanel( )
12 {
13 this.commandList = new Array(5);
14 this.buttonList = new Array(5);
15 }
16
17 public function setCommand(nSlot:int, c:ICommand):void
18 {
19 this.commandList[nSlot] = c;
20 }
21
22 public function setButton(nSlot:int, sName:String):void
23 {
24 var btn:TextButton = new TextButton(sName);
25 this.buttonList[nSlot] = btn;
26 btn.x = nSlot * 100;
27 btn.addEventListener(MouseEvent.CLICK, this.buttonClicked);
28 this.addChild(btn);
29 }
30
31 private function buttonClicked(e:Event)
32 {
33 for (var i:int = 0; i < buttonList.length; i++)
34 {
35 if (buttonList[i] === e.target)
36 {
37 this.commandList[i].execute( );
38 break;
39 }
40 }
Free download pdf