Categories
Articles

Basic Parsley MVC Flash Builder Actionscript Project

This is a basic model view controller example of a Parsley Actionscript project created in Flash Builder. I posted in this blog a minimalist example of using Parsley without implementing model view controller. See Parsley Hello World For A Flash Builder Actionscript Project.. In that post I explained the messaging in Parsley and will not repeat that explanation in this post other than to point them out where used in the model view controller implementation.

This model view controller example is as basic as I can make it while best trying to show the decoupling magic in Parsley. This is accomplished using the Parsley messaging and injection. I attempted to keep the view decoupled from the controller and model. The model and the controller could be decoupled from each other. How far you go with this depends on how many messages you want to design. To keep simple I did have the controller include the model and directly call model methods. This could be decoupled with a Parsley message.

This example follows a few techniques in a referenced example found in the Spicefactory Parsley Developer Manual in chapter 1 under “Other Resources”. This example is found at BloggingLemon. It was written in July 2009. There is a live demo and you can view the source code. Unfortunately the article has no explanations. It did provide me a good template for the Parsley bootstrapping. I tried to streamline that example even further and document what I know here.

You can build this with the free Flex SDK by using the code in the src folder and be sure to include a path to the Parsley and Spicelib library. I have included the Flash Builder 4 project file here you can download.

[ad name=”Google Adsense”]
Application Class – ParsleyFramework_MVC_AS.as

This is the bootstrap application class. One of the issues in Flash using the XML Parsley configuration file are classes not tied to the view. These classes need to be compiled early so that Parsley can reflect on them. In our case the ApplicationModel and ApplicationController classes fall into this category. There are three techniques to include them for Parsley and I repeated the Parsley Developer’s Manual notes in the comments on line 35 – 39. I borrowed the first technique also used in the BloggingLemon example which is considered by some a hack. Line 41 shows including these classes in an array that has no other use in this class and seems simple enough but should be clearly documented so they are not removed as orphaned code.

Lines 53 – 60 configure the Parsley log messaging useful for debugging Parsley. Here we are suppressing the Parsley messaging so you can view the trace statements I added to help follow the application model view controller and Parsely messaging.

Lines 89 and 90 of the initApp method load the Parsley xml configuration file shown later in this post.

Lines 100 and 103 of the contextEventInitializedHandler method create Parsley managed objects for the two views in this application. The input view allows you to enter and send a message. The output view is a Flash TextField that shows all the messages in reverse entry order. Actually the ApplicationModel maintains the reverse order and the view only displays the model.

The trace statements will show you the flow of the class as it bootstraps.

package
{
	import controllers.ApplicationController;
	
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	
	import models.ApplicationModel;
	
	import org.spicefactory.lib.flash.logging.Appender;
	import org.spicefactory.lib.flash.logging.FlashLogFactory;
	import org.spicefactory.lib.flash.logging.LogLevel;
	import org.spicefactory.lib.flash.logging.impl.DefaultLogFactory;
	import org.spicefactory.lib.flash.logging.impl.TraceAppender;
	import org.spicefactory.lib.logging.LogContext;
	import org.spicefactory.lib.logging.Logger;
	import org.spicefactory.parsley.core.context.Context;
	import org.spicefactory.parsley.core.events.ContextEvent;
	import org.spicefactory.parsley.flash.logging.FlashLoggingXmlSupport;
	import org.spicefactory.parsley.xml.XmlContextBuilder;
	
	import views.InputView;
	import views.OutputView;

	[SWF(frameRate="30", width="800", height="650", backgroundColor="0x666666")]	
	
	public class ParsleyFramework_MVC_AS extends Sprite
	{
		/**
		 * Hack to force compiling of classes configured in ParsleyConfiguration.xml 
		 * not used in this class so Parsley can reflect on them. 
		 * 
		 * Alternatives to this hack include either 
		 * compiling them into an SWC (with compc you can include 
		 * whole source folders into the SWC) and then include the whole SWC into your SWF 
		 * with the -include-libraries option of the mxmlc compiler.
		 * or include individual classes with the -includes option of the mxmlc compiler. 
		 * */
		protected var classImporter:Array = [ApplicationModel, ApplicationController];
		/**
		 * This app's context for Parsley.
		 * */
		protected var mainContext:Context;
		/**
		 * Application bootstrap class.
		 * */
		public function ParsleyFramework_MVC_AS()
		{
			super();
			trace("INIT: ParsleyFramework_MVC_AS()");
			var factory:FlashLogFactory = new DefaultLogFactory();
			// Spicefactory warning level for logging.
			factory.setRootLogLevel(LogLevel.WARN);
			var traceApp:Appender = new TraceAppender();
			// Suppress SpiceFactory lib tracing.
			traceApp.threshold = LogLevel.OFF;
			factory.addAppender(traceApp);
			LogContext.factory = factory;
			if (stage == null) 
			{
				addEventListener(Event.ADDED_TO_STAGE, addedToStageEventHandler);
			}
			else 
			{
				initApp();
			}
		}
		/**
		 * Handler for ADDED_TO_STAGE EVENT
		 */
		protected function addedToStageEventHandler(event:Event):void
		{
			trace("INIT: ParsleyFramework_MVC_AS.addedToStageEventHandler(...)");
			removeEventListener(Event.ADDED_TO_STAGE, addedToStageEventHandler);
			initApp();
		} 
		/**
		 * Initialize the stage and load Parsley configuration.
		 */
		protected function initApp():void
		{            
			trace("INIT: ParsleyFramework_MVC_AS.initApp()");
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			FlashLoggingXmlSupport.initialize();
			// INITIALIZE CONTEXT
			mainContext = XmlContextBuilder.build("ParsleyConfiguration.xml");
			mainContext.addEventListener(ContextEvent.INITIALIZED, contextEventInitializedHandler); 
		}
		/**
		 * Handler for Parsley ContextEvent.INITIALIZED event.
		 */
		protected function contextEventInitializedHandler(event:ContextEvent):void
		{    
			trace("INIT: ParsleyFramework_MVC_AS.contextEventInitializedHandler(...)");
			mainContext.removeEventListener(ContextEvent.INITIALIZED, contextEventInitializedHandler);
			// Add in the views.
			var inputView:InputView = mainContext.getObjectByType(InputView) as InputView;
			addChild(inputView);  
			inputView.y = 50;
			var outputView:OutputView = mainContext.getObjectByType(OutputView) as OutputView;
			addChild(outputView);  
			outputView.y = inputView.y + inputView.height + 5;
		}        
	}
}

Parsley Configuration XML File – ParsleyConfiguration.xml
For Parsley to look for the Parsley metatags and other management tasks, it needs to know which classes to search. Loading an XML configuration file is how that is done. Here you see the model, controller and two views referenced by their package identification.

<?xml version="1.0" encoding="UTF-8"?>
<objects 
    xmlns="http://www.spicefactory.org/parsley"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.spicefactory.org/parsley 
        http://www.spicefactory.org/parsley/schema/2.3/parsley-core.xsd"
    >
     <!-- Objects managed by Parsley -->
 	<object type="models.ApplicationModel" />
 	<object type="controllers.ApplicationController" />
     
	<object type="views.InputView" />
	<object type="views.OutputView"  /> 
</objects>

[ad name=”Google Adsense”]
The Input View – InputView.as
This is an input TextField and an extended SimpleButton to take any typed message and send a Parsley message.

Line 102 is where a message is dispatched for Parsley to broadcast. Lines 37 and 38 show the Parsley injection for the messaging method.

There is no reference to a controller or a model in this view. The message on line 102 is dispatched for the chosen controller to handle. That choice is made in the controller.

package views
{
	import events.SendTextMessageEvent;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flashx.textLayout.formats.TextAlign;
	import ui.simple.QuickButton;
	/**
	 * Demonstrates UI components sending messages confined to this view while
	 * using Parsley to send the SendTextMessageEvent outside for a controller to handle.
	 * */
	public class InputView extends Sprite
	{
		/**
		 * Output TextField component.
		 * */
		private var input_tf:TextField;
		/**
		 * TextFormat for input_tf.
		 * */
		private var tfFormat:TextFormat;
		/**
		 * The send button
		 * */
		private var sendButton:QuickButton;
		/**
		 * The off button
		 * */
		private var offButton:QuickButton;
		/**
		 * Parsley injected message dispatcher
		 * */
		[MessageDispatcher]
		public var dispatcher:Function;
		/**
		 * Constructor
		 * */
		public function InputView()
		{
			trace("VIEW: InputView()");
			super();
			createChildren();
		}
		/**
		 * Parsley calls automatically after context parsing.
		 */
		[Init]
		public function parsleyInit():void
		{
			trace("VIEW: InputView.parsleyInit()");
		}
		/**
		 * Build the UI for this display object.
		 */
		public function createChildren():void
		{
			trace("VIEW: InputView.createChildren()");
			// TextFormat
			tfFormat = new TextFormat();
			tfFormat.align = TextAlign.LEFT;
			tfFormat.bold = true;
			tfFormat.font = "_typewriter";
			// Input TextField.
			input_tf = new TextField();
			input_tf.border = true; 
			input_tf.multiline = false;
			input_tf.type = TextFieldType.INPUT;
			input_tf.background = true;
			input_tf.width = 600;
			input_tf.height = 20;
			input_tf.addEventListener(Event.CHANGE, input_tf_changeHandler);
			addChild(input_tf);	
			// Create QuickButton and add to display list.
			sendButton = new QuickButton("Send",60);
			sendButton.addEventListener(MouseEvent.CLICK, sendButtonClickHandler);
			addChild(sendButton);	
			input_tf.width -= sendButton.width + 10;
			sendButton.x = input_tf.x + input_tf.width + 10;
		}
		/**
		 * Handler for input_tf_changeHandler Event.CHANGE. To maintain format while changing input
		 * text.
		 * */
		private function input_tf_changeHandler(e:Event):void
		{
			//trace("VIEW: InputView.input_tf_changeHandler(...)");
			input_tf.setTextFormat(tfFormat);
		}
		/**
		 * Handler for sendButton MouseEvent.CLICK
		 * */
		private function sendButtonClickHandler(e:MouseEvent):void
		{
			trace("VIEW: InputView.sendButtonClickHandler(...)");
			// There is text to send
			if (input_tf.length > 0)
			{
				dispatcher( new SendTextMessageEvent(SendTextMessageEvent.SEND, input_tf.text) );
				input_tf.text = "";
				stage.focus = input_tf;
			}
		}
	}
}

The Output View – OutputView.as

As in the InputView there is no reference to a controller or a model. Line 68 shows using Parsley to pick up a message. Of course in a model-view-controller implementation the model should dispatch this message when the model updates.

package views
{
	import events.SendTextMessageEvent;
	import events.SentTextMessagesUpdateEvent;
	
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	
	import flashx.textLayout.formats.TextAlign;

	/**
	 * Simple output view. Demonstrates receiving Parsley managed messages and updating from model changes.
	 * */
	public class OutputView extends Sprite
	{
		/**
		 * Output TextField component.
		 * */
		private var output_tf:TextField;
		/**
		 * TextFormat for output_tf.
		 * */
		private var tfFormat:TextFormat;
		/**
		 * Constructor
		 * */
		public function OutputView()
		{
			trace("VIEW: OutputView()");
			super();
			createChildren();
		}
		/**
		 * Parsley calls automatically after context parsing.
		 */
		[Init]
		public function parsleyInit():void
		{
			trace("VIEW: OutputView.parsleyInit()");
		}
		/**
		 * Build the UI for this display object.
		 */
		public function createChildren():void
		{
			trace("VIEW: OutputView.createChildren()");
			// TextFormat
			tfFormat = new TextFormat();
			tfFormat.align = TextAlign.LEFT;
			tfFormat.bold = true;
			tfFormat.font = "_typewriter";
			// TextField.
			output_tf = new TextField();
			output_tf.border = true; 
			output_tf.multiline = true;
			output_tf.background = true;
			output_tf.width = 600;
			output_tf.height = 100;
			addChild(output_tf);
		}
		/**
		 * Parsley event handler. Listening for SentTextMessagesUpdateEvent.UPDATE type. Shows using a selector.
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler(selector="event.SentTextMessagesUpdateEvent.UPDATED")]
		public function sentTextMessagesUpdateEventHandler(event:SentTextMessagesUpdateEvent):void
		{
			trace("VIEW: OutputView.sentTextMessagesUpdateEventHandler(...) - event.type: " + event.type);
			output_tf.text = event.sentTextMessages;
			output_tf.setTextFormat(tfFormat);
		} 
	}
}

The Model – ApplicationModel.as

On line 12 of the model the one data element, sentTextMessages, holds all the text messages sent in the application. The addSentTextMessage method is where the model is updated with new text messages and where sentTextMessages is maintained. The text messages in sentTextMessages are kept in “last in” order.

Line 30 notifies the Parsley framework of changes in sentTextMessages. The wiring we applied in the Parsley framework incudes the views and the views have handlers to receive the message. In our case it is the OutputView which simply displays the sentTextMessages value as is.

package models
{
	import events.SentTextMessagesUpdateEvent;
	/**
	 * The model responsible for application data.
	 * */
	public class ApplicationModel
	{
		/**
		 * All text messages sent separated by new line \n.
		 * */
		private var sentTextMessages:String = "";
		/**
		 * Parsley injected message dispatcher
		 * */
		[MessageDispatcher]
		public var dispatcher:Function;
		/**
		 * Updates the sentTextMessages property and broadcasts SentTextMessagesUpdateEvent.
		 * @param messageText A text message sent.
		 * */
		public function addSentTextMessage(messageText:String):void
		{
			trace("MODEL: ApplicationModel.addSentTextMessage(...)");
			if (sentTextMessages.length > 0)
			{
				messageText += "\n";
			}
			sentTextMessages = messageText + sentTextMessages;
			dispatcher( new SentTextMessagesUpdateEvent(SentTextMessagesUpdateEvent.UPDATED, sentTextMessages) );
		}
	}
}

[ad name=”Google Adsense”]
The Controller– ApplicationController.as

Lines 34 and 35 uses the Parsley messaging to listen for view messages and in this case the event.SendTextMessageEvent.SEND message. Views do not need to couple to this controller. Neither does the controller need to know anything about the views.

Line 38 shows the updating of the model. However you could replace this with Parsley messaging to decouple the controller from the model. I did not in order to reduce the number of messages for the example.

package controllers
{
	import events.SendTextMessageEvent;
	
	import models.ApplicationModel;

	/**
	 * The controller responsible for application level control.
	 * */
	public class ApplicationController
	{
		/**
		 * The model injected by Parsley.
		 * */
		[Inject]
		public var model:ApplicationModel;
		/**
		 * Parsley injected message dispatcher
		 * */
		[MessageDispatcher]
		public var dispatcher:Function;
		/**
		 * Parsley calls automatically after context parsing.
		 */
		[Init]
		public function parsleyInit():void
		{
			trace("CONTROLLER: ApplicationController.parsleyInit()");
		}
		/**
		 * Parsley event handler. Listening for SendTextMessageEvent.SEND type. Shows using a selector.
		 * Other Parsley managed views can do the same.
		 */
		[MessageHandler(selector="event.SendTextMessageEvent.SEND")]
		public function sendTextMessageEventHandler(event:SendTextMessageEvent):void
		{
			trace("CONTROLLER: ApplicationController.sendTextMessageEventHandler(...) - event.type: " + event.type);
			model.addSentTextMessage(event.messageText);
		} 
	}
}

The SendTextMessageEvent– SendTextMessageEvent.as

This is a custom Actionscript event. The purpose is to carry a new text message.

package events
{
	import flash.events.Event;
	/**
	 * Event for demonstrating Parsley. View sending a new text message.
	 * */
	public class SendTextMessageEvent extends Event
	{
		/**
		 * The event send type.
		 * */
		public static const SEND:String = "event.SendTextMessageEvent.SEND";
		/**
		 * The text sent.
		 * */
		public var messageText:String;
		/**
		 * Constructor
		 * @param messageText The text sent.
		 * */
		public function SendTextMessageEvent(type:String, messageText:String, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.messageText = messageText;
			trace ("EVENT: SendTextMessageEvent(...) type: " + type);
		}
		override public function clone():Event
		{
			return new SendTextMessageEvent(type, messageText, bubbles, cancelable);
		}
	}
}

The SentTextMessagesUpdateEvent – SentTextMessagesUpdateEvent .as

Another custom Actionscript event. The model’s sentTextMessages property is carried in this event.

package events
{
	import flash.events.Event;
	/**
	 * Event for demonstrating Parsley with mvc. Model notification of sentTextMessages updated. 
	 * The event does not need to be specific to the model so references to the model in
	 * documentation is for helping in tracing the Parsley mvc being demonstrated.
	 * */
	public class SentTextMessagesUpdateEvent extends Event
	{
		/**
		 * The event updated type.
		 * */
		public static const UPDATED:String = "event.SentTextMessagesUpdateEvent.UPDATED";
		/**
		 * The model value of all the sent text messages.
		 * */
		public var sentTextMessages:String;
		/**
		 * Constructor
		 * @param sentTextMessages The model's value of the sentTextMessages.
		 * */
		public function SentTextMessagesUpdateEvent(type:String, sentTextMessages:String, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.sentTextMessages = sentTextMessages;
			trace ("EVENT: SentTextMessagesUpdateEvent(...) type: " + type);
		}
		override public function clone():Event
		{
			return new SentTextMessagesUpdateEvent(type, sentTextMessages, bubbles, cancelable);
		}
	}
}

The QuickButton- QuickButton.as
This is just an Actionscript SimpleButton to use for the demo.

package ui.simple
{
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	public class QuickButton extends SimpleButton
	{
		/**
		 * The up state background color;
		 * */
		private var upColor:uint   = 0xFFCC00;
		/**
		 * The over state background color;
		 * */
		private var overColor:uint = 0xCCFF00;
		/**
		 * The down state background color;
		 * */
		private var downColor:uint = 0x00CCFF;
		/**
		 * Width.
		 * */
		private var buttonWidth:Number;;
		/**
		 * Label.
		 * */
		private var label:String;
		/**
		 * Constructor.
		 * @param label The caption for button.
		 * @param buttonWidth Width of the button. Height is 1/3 of buttonWidth
		 * */
		public function QuickButton(label:String = "Button", buttonWidth:Number = 80)
		{
			trace("UI: QuickButton() - label: " + label);
			this.label = label;
			this.buttonWidth = buttonWidth;
			downState      = new QuickButtonDisplayShape(label, downColor, buttonWidth);
			overState      = new QuickButtonDisplayShape(label, overColor, buttonWidth);
			upState        = new QuickButtonDisplayShape(label, upColor, buttonWidth);
			hitTestState   = new QuickButtonDisplayShape(label, upColor, buttonWidth);
			useHandCursor  = true;
		}
	}
}

The QuickButton Skin – QuickButtonDisplayShape.as
How I skinned the QuickButton.

package ui.simple
{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flashx.textLayout.formats.TextAlign;
	/**
	 * Rounded button with text label. Width and height and not margins or padding.
	 * */
	public class QuickButtonDisplayShape extends Sprite
	{
		/**
		 * Background color.
		 * */
		private var bgColor:uint;
		/**
		 * Width.
		 * */
		private var buttonWidth:Number;
		/**
		 * Height.
		 * */
		private var buttonHeight:Number;
		/**
		 * Label TextField component.
		 * */
		private var tf:TextField;
		/**
		 * Left padding for tf inside the button shape.
		 * */
		private const TF_LEFT_PADDING:Number = 6;
		/**
		 * Right padding for tf inside the button shape.
		 * */
		private const TF_RIGHT_PADDING:Number = 6;
		/**
		 * Ratio of button height to the buttonWidth.
		 * */
		private const BUTTON_HEIGHT_RATIO:Number = 1/3;
		/**
		 * Constructor.
		 * @param label The caption for button.
		 * @param bgColor Color for the button background.
		 * @param buttonWidth Width of the button. Height is 1/3 of buttonWidth
		 * */
		public function QuickButtonDisplayShape(label:String,bgColor:Number, buttonWidth:Number)
		{
			// Consume parameters
			this.bgColor = bgColor;
			this.buttonWidth = buttonWidth;
			this.buttonHeight = buttonWidth * BUTTON_HEIGHT_RATIO;
			// Draw button graphics.
			draw();
			// TextField for the button caption.
			tf = new TextField();
			var tfFormat:TextFormat = new TextFormat();
			tf.text = label;
			// Format for centering.
			tfFormat.align = TextAlign.CENTER;
			tfFormat.bold = true;
			tfFormat.font = "_sans";
			//tf.border = true; // Design guide for layout.
			tf.setTextFormat(tfFormat);
			// Position and size the caption.
			tf.x = TF_LEFT_PADDING;
			tf.width = buttonWidth - (TF_LEFT_PADDING + TF_RIGHT_PADDING);
			tf.height = tf.textHeight + 2;
			tf.y = Math.max(0, ( buttonHeight - (tf.textHeight + 4)) / 2);
			// Add caption.
			addChild(tf);
		}
		/**
		 * Draw graphics.
		 * */
		private function draw():void 
		{
			graphics.beginFill(bgColor);
			graphics.drawRoundRect(0, 0, buttonWidth, buttonHeight, 20, 20);
			graphics.endFill();
		}
	}
}