ActionScript 3.0 Design Patterns

(Chris Devlin) #1

242 | Chapter 6: Composite Pattern


Example 6-27 shows the modifiedMainWingclass. Note the conditional statement in


lines 22- 26. If the damage exceeds 50, this node removes itself from the display list


(and the airplane composite structure) by callingremoveChildin its parent. Before we


can test our modified components, a few changes to the Main class are necessary to


display total damage.


Calculating Total Damage to the Airplane


In the interests of keeping the example simple, we will register a mouse click handler


calledshowDamageto thestageto display the total damage to the airplane. The follow-


ing statement needs to be added at the end of the constructor in theMainclass shown


in Example 6-25.


stage.addEventListener(MouseEvent.CLICK, showDamage);

In addition, the followingshowDamageevent handler method should be added to the


Main class as well.


Example 6-27. MainWing.as with modifiedMainWing class


1 package
2 {
3 import flash.events.*;
4
5 public class MainWing extends Composite
6 {
7 public function MainWing(weight:Number, damage:Number = 0)
8 {
9 graphics.lineStyle(25, 0x999999);
10 graphics.moveTo(0, 0);
11 graphics.lineTo(100, 0);
12
13 addEventListener(MouseEvent.CLICK, doDamage);
14
15 super(weight, damage);
16 }
17
18 private function doDamage(evt:Event)
19 {
20 this.nDamage += 20;
21 trace('Damage to this wing is now ' + this.nDamage);
22 if (this.nDamage > 50)
23 {
24 trace('Wing detached from fuselage - fatal crash!');
25 parent.removeChild(this);
26 }
27 evt.stopPropagation( );
28 // stop event propegation to subsequent nodes
29 }
30 }
31 }
Free download pdf