<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>devahead BLOG</title>
	<atom:link href="http://www.devahead.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.devahead.com/blog</link>
	<description>Adobe Flex, Flash Platform and everything else about software development from a developer&#039;s point of view</description>
	<lastBuildDate>Sat, 15 May 2010 20:35:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Setter is not invoked when a bindable Flex property doesn&#8217;t change</title>
		<link>http://www.devahead.com/blog/2010/05/setter-is-not-invoked-when-a-bindable-flex-property-doesnt-change/</link>
		<comments>http://www.devahead.com/blog/2010/05/setter-is-not-invoked-when-a-bindable-flex-property-doesnt-change/#comments</comments>
		<pubDate>Sat, 15 May 2010 20:35:35 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[bindable]]></category>
		<category><![CDATA[getter]]></category>
		<category><![CDATA[property]]></category>
		<category><![CDATA[setter]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=29</guid>
		<description><![CDATA[You&#8217;ve probably been using the Bindable metadata tag a lot of times with properties in your Flex applications. When a property is defined through getter and setter functions, you may take for granted that each time you set the value of the property, the corresponding setter is invoked, so you can perform your own operations [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/SetterNotInvokedWithBindable/SetterNotInvokedWithBindable.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/SetterNotInvokedWithBindable/srcview/SetterNotInvokedWithBindable.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p style="padding-top:10px">You&#8217;ve probably been using the <em>Bindable</em> metadata tag a lot of times with properties in your Flex applications. When a property is defined through getter and setter functions, you may take for granted that each time you set the value of the property, the corresponding setter is invoked, so you can perform your own operations in it. Well, this is not totally true with bindable properties. What I&#8217;m going to show is just something to remember whenever you use the <em>Bindable</em> metadata tag with properties defined through getter and setter. It is much easier to explain everything if we immediately look at the example application.</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Setter is not invoked when a bindable Flex property doesn\'t change - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;
	viewSourceURL=&quot;srcview/index.html&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			private var _notBindableProp: String = &quot;&quot;;

			public function get notBindableProp(): String
			{
				return _notBindableProp;
			}

			public function set notBindableProp(value: String): void
			{
				_notBindableProp = value;

				logValueChange(&quot;notBindableProp&quot;, _notBindableProp);
			}

			private var _bindableProp: String = &quot;&quot;;

			[Bindable]
			public function get bindableProp(): String
			{
				return _bindableProp;
			}

			public function set bindableProp(value: String): void
			{
				_bindableProp = value;

				logValueChange(&quot;bindableProp&quot;, _bindableProp);
			}

			private var _bindableEventProp: String = &quot;&quot;;

			[Bindable(&quot;bindableEventPropChanged&quot;)]
			public function get bindableEventProp(): String
			{
				return _bindableEventProp;
			}

			public function set bindableEventProp(value: String): void
			{
				_bindableEventProp = value;

				logValueChange(&quot;bindableEventProp&quot;, _bindableEventProp);

				dispatchEvent(new Event(&quot;bindableEventPropChanged&quot;));
			}

			protected function logValueChange(propertyName: String, newValue: String): void
			{
				logArea.text += propertyName + &quot; setter invoked: &quot; + newValue + &quot;\n&quot;;
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:Form&gt;
		&lt;mx:FormItem direction=&quot;horizontal&quot;
			label=&quot;New value for the NOT BINDABLE property:&quot;&gt;
			&lt;mx:TextInput id=&quot;notBindablePropText&quot; width=&quot;150&quot;/&gt;
			&lt;mx:Button label=&quot;Set&quot; click=&quot;{notBindableProp = notBindablePropText.text}&quot;/&gt;
		&lt;/mx:FormItem&gt;

		&lt;mx:FormItem direction=&quot;horizontal&quot;
			label=&quot;New value for the BINDABLE property:&quot;&gt;
			&lt;mx:TextInput id=&quot;bindablePropText&quot; width=&quot;150&quot;/&gt;
			&lt;mx:Button label=&quot;Set&quot; click=&quot;{bindableProp = bindablePropText.text}&quot;/&gt;
			&lt;mx:Label text=&quot;{bindableProp}&quot; fontWeight=&quot;bold&quot;/&gt;
		&lt;/mx:FormItem&gt;

		&lt;mx:FormItem direction=&quot;horizontal&quot;
			label=&quot;New value for the BINDABLE property WITH CUSTOM EVENT:&quot;&gt;
			&lt;mx:TextInput id=&quot;bindableEventPropText&quot; width=&quot;150&quot;/&gt;
			&lt;mx:Button label=&quot;Set&quot; click=&quot;{bindableEventProp = bindableEventPropText.text}&quot;/&gt;
			&lt;mx:Label text=&quot;{bindableEventProp}&quot; fontWeight=&quot;bold&quot;/&gt;
		&lt;/mx:FormItem&gt;
	&lt;/mx:Form&gt;

	&lt;mx:Label text=&quot;Log:&quot;/&gt;

	&lt;mx:TextArea id=&quot;logArea&quot; width=&quot;400&quot; height=&quot;300&quot;/&gt;

&lt;/mx:Application&gt;
</pre>
</div>
<p>The property called <em>notBindableProp</em> is just a simple not bindable property. Whenever you set its value, the setter is invoked. <em>bindableProp</em> is a standard bindable property. If you try to set its value, you&#8217;ll quickly find out that <strong>the setter is invoked only if the new value is different from the value returned by the corresponding getter</strong>. So you cannot rely on doing something inside the setter when the new value is exactly the same as the previous one. What if you still want a bindable property, but you need to perform some operations in the setter every time a value is set, even if it&#8217;s equal to the previous one? You can simply define a custom event name in the <em>Bindable</em> metadata tag as you can see in the <em>bindableEventProp</em>. Every time a value is set for that property, the setter is invoked and you can perform your operations and then dispatch your own event.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2010/05/setter-is-not-invoked-when-a-bindable-flex-property-doesnt-change/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Disabling user interaction in a Flex application</title>
		<link>http://www.devahead.com/blog/2010/04/disabling-user-interaction-in-a-flex-application/</link>
		<comments>http://www.devahead.com/blog/2010/04/disabling-user-interaction-in-a-flex-application/#comments</comments>
		<pubDate>Sat, 24 Apr 2010 00:04:11 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[interaction]]></category>
		<category><![CDATA[user]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=23</guid>
		<description><![CDATA[While working with asynchronous operations like server calls or asynchronous events, you know that it&#8217;s not easy to guarantee a correct processing of user&#8217;s requests if there isn&#8217;t a well defined workflow that the user must follow. For example: the user clicks a button that makes a function call on the server side, so the [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/UserInteractionManagerDemo/UserInteractionManagerDemo.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/UserInteractionManagerDemo/srcview/UserInteractionManagerDemo.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p style="padding-top:10px">While working with asynchronous operations like server calls or asynchronous events, you know that it&#8217;s not easy to guarantee a correct processing of user&#8217;s requests if there isn&#8217;t a well defined workflow that the user must follow. For example: the user clicks a button that makes a function call on the server side, so the application waits for the server to reply, but meanwhile the application is still responsive for the user so any other operation could be performed by the user on the interface possibly not compatible with the reply of the server in the moment that the client receives it. <strong>There are times when the user interaction must be disabled</strong> until the application is again in a state that can safely process any other user request because there&#8217;s a well defined workflow to follow. This is the topic of this post, giving you <strong>a way to temporarily disable user interaction while the application is not in a <em>ready</em> state</strong>.</p>
<p>At this point one could think: well, that&#8217;s easy, you can do that simply by setting the <em>enabled</em> property of the components. No, it&#8217;s not that easy. The reason why it&#8217;s not easy, is because <strong>you don&#8217;t want the user to see weird color changes in the user interface</strong> because a component switches from <em>enabled</em> to <em>disabled</em> state and vice versa and <strong>you want to keep the focus on the component that was focused before disabling the interface</strong>. So these are the key points that I had to keep in mind while thinking about the solution that I&#8217;m going to show you.</p>
<p>As usual, the best way to start is looking at the source code, so we can discuss later about what it does.</p>
<div class="post-source-code">
<pre class="brush: as3;">
package com.devahead.utils
{
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.EventDispatcher;

	import mx.collections.ArrayCollection;
	import mx.containers.Canvas;
	import mx.core.Application;
	import mx.core.IChildList;
	import mx.core.UIComponent;

	public class UserInteractionManager extends EventDispatcher
	{
		protected var _blocker: Canvas = null;

		protected var _managedApp: Application = null;

		/**
		 * Application managed by this UserInteractionManager instance.
		 */
		public function get managedApp(): Application
		{
			return _managedApp;
		}

		protected var _focusState: Object = null;

		/**
		 * Data about the focused components before disabling the
		 * user interaction.
		 */
		protected function get focusState(): Object
		{
			return _focusState;
		}

		protected function set focusState(value: Object): void
		{
			_focusState = value;

			dispatchEvent(new Event(&quot;isInteractionEnabledChanged&quot;));
		}

		/**
		 * Tells if the user interaction is currently enabled.
		 */
		[Bindable(&quot;isInteractionEnabledChanged&quot;)]
		public function get isInteractionEnabled(): Boolean
		{
			return (_focusState == null);
		}

		/**
		 * Constructor.
		 *
		 * @param managedApp
		 *   Application instance managed by UserInteractionManager.
		 */
		public function UserInteractionManager(managedApp: Application)
		{
			_managedApp = managedApp;

			// Create the blocker component to avoid mouse clicks.
			// We set a backgroundColor to actually allow the clicks to be blocked
			// (it doesn't work if the blocker is totally transparent) and we set
			// the backgroundAlpha to a very small number so the blocker is not
			// transparent for the Flash player but it is actually invisible for the
			// human eye.
			_blocker = new Canvas();
			_blocker.setStyle(&quot;backgroundColor&quot;, 0xffffff);
			_blocker.setStyle(&quot;backgroundAlpha&quot;, 0.01);
		}

		/**
		 * Disable the user interaction with the application.
		 */
		public function disableUserInteraction(): void
		{
			// Check if interaction is already disabled
			if (!isInteractionEnabled) return;

			// Save the information about the current focused component
			focusState = new Object();

			if (_managedApp.focusManager != null)
			{
				focusState.focusedComponent = _managedApp.focusManager.getFocus();

				if (focusState.focusedComponent != null &amp;&amp;
					focusState.focusedComponent.hasOwnProperty(&quot;selectionBeginIndex&quot;) &amp;&amp;
					focusState.focusedComponent.hasOwnProperty(&quot;selectionEndIndex&quot;))
				{
					// Save the selection information about the focused component (useful for text
					// selection inside a TextInput for example).
					focusState.focusedCompSelectionBeginIndex = focusState.focusedComponent.selectionBeginIndex;
					focusState.focusedCompSelectionEndIndex = focusState.focusedComponent.selectionEndIndex;
				}
			}

			// Set the size of the blocker
			_blocker.width = _managedApp.width;
			_blocker.height = _managedApp.height;

			// Make the blocker the topmost component in the display list
			var rawChildren: IChildList = _managedApp.systemManager.rawChildren;

			if (rawChildren.contains(_blocker))
			{
				rawChildren.removeChild(_blocker);
			}

			rawChildren.addChild(_blocker);

			if (_managedApp.stage != null)
			{
				// Remove the focus from the current focused component
				_managedApp.stage.focus = null;
			}

			if (_managedApp.systemManager is DisplayObjectContainer)
			{
				// Disable tabbing so the user cannot use the tab key to cycle
				// among the components.
				focusState.sysManTabChildren = (_managedApp.systemManager as DisplayObjectContainer).tabChildren;
				(_managedApp.systemManager as DisplayObjectContainer).tabChildren = false;
			}
		}

		/**
		 * Restore the user interaction with the application.
		 */
		public function restoreUserInteraction(): void
		{
			// Check if the interaction is already enabled
			if (isInteractionEnabled) return;

			if (_managedApp.systemManager is DisplayObjectContainer)
			{
				// Restore the tabbing state saved before disabling the user interaction
				(_managedApp.systemManager as DisplayObjectContainer).tabChildren = focusState.sysManTabChildren;
			}

			// Remove the blocker from the display list
			var rawChildren: IChildList = _managedApp.systemManager.rawChildren;

			if (rawChildren.contains(_blocker))
			{
				rawChildren.removeChild(_blocker);
			}

			if (focusState.hasOwnProperty(&quot;focusedComponent&quot;) &amp;&amp;
				focusState.focusedComponent != null &amp;&amp;
				_managedApp.focusManager != null)
			{
				// Check if I can restore the focus or not depending on whether or not there
				// are modal popups over the previously focused component.
				var canRestoreFocus: Boolean = false;

				if (_managedApp.systemManager.numModalWindows &gt; 0)
				{
					// Get the list of all the active popups
					var popupList: ArrayCollection = PopUpUtils.getAllPopups(_managedApp, true);

					if (popupList.length == 0)
					{
						// There are no popups, so I can restore the focus
						canRestoreFocus = true;
					}
					else
					{
						if (focusState.focusedComponent is UIComponent)
						{
							// Get the topmost popup
							var topmostPopup: Object = popupList.getItemAt(popupList.length - 1);

							var currParent: Object = (focusState.focusedComponent as UIComponent).parent;

							// Go through all the parents hierarchy for the component that should be
							// focused to check if it belongs to the topmost popup.
							while (currParent != null)
							{
								if (currParent == topmostPopup)
								{
									// The component that should be focused belongs to the topmost popup,
									// so I can restore the focus.
									canRestoreFocus = true;
									break;
								}

								if (currParent == currParent.parent)
								{
									break;
								}

								currParent = currParent.parent;
							}
						}
						else
						{
							canRestoreFocus = true;
						}
					}
				}
				else
				{
					// There are no modal popups, so I can always restore the focus
					canRestoreFocus = true;
				}

				if (canRestoreFocus)
				{
					// Restore the focus on the component that was focused before disabling the
					// user interaction.
					_managedApp.focusManager.setFocus(focusState.focusedComponent);

					if (focusState.focusedComponent.hasOwnProperty(&quot;selectionBeginIndex&quot;) &amp;&amp;
						focusState.focusedComponent.hasOwnProperty(&quot;selectionEndIndex&quot;))
					{
						// Restore the selection inside the focused component (useful for TextInput
						// for example).
						focusState.focusedComponent.selectionBeginIndex = focusState.focusedCompSelectionBeginIndex;
						focusState.focusedComponent.selectionEndIndex = focusState.focusedCompSelectionEndIndex;
					}
				}
			}

			focusState = null;
		}
	}
}
</pre>
</div>
<p>This is the <em class="highlight">UserInteractionManager</em> class and it manages all the necessary operations for you to disable and restore the user interaction. The constructor accepts the application that has to be managed by an instance of the class, so you&#8217;ll have a single instance of <em>UserInteractionManager</em> for an application. There are two functions in the class, <em>disableUserInteraction</em> and <em>restoreUserInteraction</em>.</p>
<p>When you decide to disable the interaction, <em>UserInteractionManager</em> saves the information about the current focused component so the focus can be restored later, then it puts a blocker canvas on top of every other child object in the application. Here we must use the <em>rawChildren</em> because the blocker must be also on top of the popups if present. After saving state information about the focused component and displaying the blocker, the focus is removed from the focused component and the <em>tabChildren</em> property of the <em>systemManager</em> is set to <em>false</em> so we ensure that the user cannot try to focus the components with the tab key. The blocker is not visible to the human eye because we set a very low <em>backgroundAlpha</em> value, but we must fill it with a color to make sure that the Flash player intercepts the mouse clicks on the blocker canvas instead of letting them go through the underlying components.</p>
<p>If you decide to restore the user interaction, then <em>UserInteractionManager</em> restores the <em>tabChildren</em> property of the <em>systemManager</em>, removes the blocker canvas and restores the focus on the previously focused component. While restoring the focus, we must also check if there are modal popups over the previously focused component. If the component is not a child of a topmost modal popup then it makes no sense to restore the focus on a component that is not supposed to have it since there&#8217;s a modal popup in front of it. To get all the popups in the application we use an utility class named <em>PopUpUtils</em> that we&#8217;ve already seen in a <a href="http://www.devahead.com/blog/2009/12/getting-all-the-popups-in-a-flex-application/">previous post</a>. The properties <em>selectionBeginIndex</em> and <em>selectionEndIndex</em> are used with a <em>TextInput</em> or similar components to restore the text selection inside the focused component if some text was selected before disabling the user interaction.</p>
<p>Let&#8217;s take a look at an example application that uses the <em>UserInteractionManager</em> class. <span id="more-23"></span></p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Disabling user interaction in a Flex application - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot; verticalGap=&quot;10&quot;
	applicationComplete=&quot;{onApplicationComplete()}&quot;
	defaultButton=&quot;{createPopupBtn}&quot;
	viewSourceURL=&quot;srcview/index.html&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			import flash.utils.setTimeout;
			import mx.containers.Panel;
			import mx.managers.PopUpManager;
			import com.devahead.utils.UserInteractionManager;

			[Bindable]
			protected var _userInteractionManager: UserInteractionManager = null;

			protected function onApplicationComplete(): void
			{
				// Create the UserInteractionManager instance for this application
				_userInteractionManager = new UserInteractionManager(this);

				systemManager.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			}

			protected function disableUserInteraction(): void
			{
				_userInteractionManager.disableUserInteraction();
			}

			protected function restoreUserInteraction(): void
			{
				_userInteractionManager.restoreUserInteraction();
			}

			protected function createPopup(): void
			{
				// Create a popup with a Panel, a couple of TextInput and a close button
				var popup: Panel = (PopUpManager.createPopUp(this, Panel, modalPopupCheck.selected) as Panel);
				popup.title = &quot;Popup panel&quot;;
				popup.addChild(new TextInput());
				popup.addChild(new TextInput());

				var popupBtn: Button = new Button();
				popupBtn.label = &quot;Close&quot;;
				popupBtn.addEventListener(MouseEvent.CLICK,
					function(event: MouseEvent): void
					{
						PopUpManager.removePopUp(popup);
					});

				popup.addChild(popupBtn);

				PopUpManager.centerPopUp(popup);
			}

			protected function onKeyUp(event: KeyboardEvent): void
			{
				// Handle the keyboard event to temporarily disable the user interaction
				if (event.keyCode == 68 &amp;&amp; event.ctrlKey &amp;&amp; event.shiftKey &amp;&amp; event.altKey)
				{
					// CTRL + SHIFT + ALT + D
					disableUserInteraction();

					// The interaction will be restored after the specified number of seconds
					setTimeout(restoreUserInteraction, Number(restoreTimeoutEdit.text) * 1000);
				}
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:Label text=&quot;{'USER INTERACTION: ' + (_userInteractionManager.isInteractionEnabled ?
		'enabled' : 'disabled')}&quot; fontWeight=&quot;bold&quot;/&gt;

	&lt;mx:Panel title=&quot;Test panel&quot; layout=&quot;vertical&quot;
		paddingTop=&quot;4&quot; paddingBottom=&quot;4&quot; paddingLeft=&quot;4&quot; paddingRight=&quot;4&quot;&gt;
		&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
			&lt;mx:Label text=&quot;Field 1:&quot;/&gt;
			&lt;mx:TextInput id=&quot;edit1&quot;/&gt;
		&lt;/mx:HBox&gt;
		&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
			&lt;mx:Label text=&quot;Field 2:&quot;/&gt;
			&lt;mx:TextInput id=&quot;edit2&quot;/&gt;
		&lt;/mx:HBox&gt;

		&lt;mx:List width=&quot;200&quot; height=&quot;150&quot; allowMultipleSelection=&quot;true&quot;&gt;
			&lt;mx:dataProvider&gt;
				&lt;mx:Array&gt;
					&lt;mx:String&gt;Item 1&lt;/mx:String&gt;
					&lt;mx:String&gt;Item 2&lt;/mx:String&gt;
					&lt;mx:String&gt;Item 3&lt;/mx:String&gt;
					&lt;mx:String&gt;Item 4&lt;/mx:String&gt;
					&lt;mx:String&gt;Item 5&lt;/mx:String&gt;
				&lt;/mx:Array&gt;
			&lt;/mx:dataProvider&gt;
		&lt;/mx:List&gt;

		&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
			&lt;mx:Button id=&quot;createPopupBtn&quot; label=&quot;Create popup&quot; click=&quot;{createPopup()}&quot;/&gt;
			&lt;mx:CheckBox id=&quot;modalPopupCheck&quot; label=&quot;Modal&quot;/&gt;
		&lt;/mx:HBox&gt;
	&lt;/mx:Panel&gt;

	&lt;mx:Label text=&quot;Disable user interaction: CTRL + SHIFT + ALT + D&quot;/&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Label text=&quot;Restore user interaction timeout (sec):&quot;/&gt;
		&lt;mx:TextInput id=&quot;restoreTimeoutEdit&quot; text=&quot;5&quot; width=&quot;40&quot;/&gt;
	&lt;/mx:HBox&gt;

&lt;/mx:Application&gt;
</pre>
</div>
<p>Basically you&#8217;ve got a few controls like <em>TextInput</em>, <em>List</em> and <em>Button</em> to interact with the application and test that the focus is correctly restored like what it was before disabling the user interaction. You can also open both modal and normal popups. The interaction can be disabled with a shortcut (CTRL + SHIFT + ALT + D) and is restored after the specified number of seconds. Make sure you click on the application and set the focus on a control before pressing the keys for the shortcut to be intercepted correctly.</p>
<p>Now, just a typical situation in which the <em>UserInteractionManager</em> class could be useful:</p>
<div class="post-source-code">
<pre class="brush: as3;">
public function makeServerCall(ro: RemoteObject): void
{
	userInteractionManager.disableUserInteraction();

	var asyncToken: AsyncToken = ro.myServerFunction();

	asyncToken.addResponder(new mx.rpc.Responder(
		onMakeServerCallOK, onMakeServerCallFault));
}

protected function onMakeServerCallOK(event: ResultEvent): void
{
	userInteractionManager.restoreUserInteraction();
}

protected function onMakeServerCallFault(event: FaultEvent): void
{
	userInteractionManager.restoreUserInteraction();
}
</pre>
</div>
<p>This is a simple example. Before making a server call you disable the user interaction and you restore it as soon as the server replies. This makes sure that the user cannot act in an unexpected way while you don&#8217;t have an answer from the server.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2010/04/disabling-user-interaction-in-a-flex-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sending ActionScript objects through BlazeDS with ASObject</title>
		<link>http://www.devahead.com/blog/2010/04/sending-actionscript-objects-through-blazeds-with-asobject/</link>
		<comments>http://www.devahead.com/blog/2010/04/sending-actionscript-objects-through-blazeds-with-asobject/#comments</comments>
		<pubDate>Sun, 18 Apr 2010 23:24:27 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[ASObject]]></category>
		<category><![CDATA[Flex]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=21</guid>
		<description><![CDATA[Typically, BlazeDS is used to send typed objects between a Flex client and a Java server, but what if you want to send generic objects generated dynamically? On the client side, you can create an ActionScript object dynamically through the Object base class. So, for example, you can write something like this:


var myObject: Object = [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="source-link"><a href="http://www.devahead.com/blog/examples/BlazeDSASObject/BlazeDSASObject.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p style="padding-top:10px">Typically, BlazeDS is used to send typed objects between a Flex client and a Java server, but what if you want to <strong>send generic objects generated dynamically</strong>? On the client side, you can create an ActionScript object dynamically through the <strong><em>Object</em></strong> base class. So, for example, you can write something like this:</p>
<div class="post-source-code">
<pre class="brush: as3;">
var myObject: Object = new Object();
myObject.prop1 = &quot;prop1Value&quot;;
myObject.prop2 = new Object();
myObject.prop2.prop21 = &quot;subValue1&quot;;
myObject.prop2.prop22 = &quot;subValue2&quot;;
</pre>
</div>
<p>Just a simple example that shows how to dynamically add custom properties to a generic ActionScript <em>Object</em>. What could not be obvious is how to obtain the same functionality on the server side with Java. In fact, the <em>Object</em> class in ActionScript corresponds to the <strong><em>ASObject</em></strong> class in Java. What is important to note is that <strong>the <em>ASObject</em> class extends <em>java.util.HashMap</em></strong>. How can this information be useful? To understand it, let&#8217;s immediately take a look at our example application.</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Sending ActionScript objects through BlazeDS with ASObject - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			import mx.rpc.events.FaultEvent;
			import mx.rpc.events.ResultEvent;
			import mx.controls.Alert;
			import mx.rpc.AsyncToken;

			protected static const ENDPOINT: String = &quot;messagebroker/amf&quot;;

			protected function getRemoteObject(): void
			{
				// Create a generic ActionScript object to send to the server
				var sentGenericObj: Object = new Object();
				sentGenericObj.prop1 = 123;
				sentGenericObj.composite = new Object();
				sentGenericObj.composite.sub1 = &quot;subValue1&quot;;
				sentGenericObj.composite.sub2 = 0.57;

				var call: AsyncToken = testService.getSentGenericObject(sentGenericObj);
				call.addResponder(new mx.rpc.Responder(
					onGetRemoteObjectOK, onGetRemoteObjectFault));
			}

			protected function onGetRemoteObjectOK(event: ResultEvent): void
			{
				var result: Object = event.result;

				Alert.show(&quot;Returned object:\n\n&quot; +
					&quot;prop1 = &quot; + result.prop1 + &quot;\n&quot; +
					&quot;composite.sub1 = &quot; + result.composite.sub1 + &quot;\n&quot; +
					&quot;composite.sub2 = &quot; + result.composite.sub2);
			}

			protected function onGetRemoteObjectFault(event: FaultEvent): void
			{
				Alert.show(&quot;Error retrieving remote object.\n\n&quot; +
					&quot;faultString: &quot; + event.fault.faultString + &quot;\n&quot; +
					&quot;faultDetail: &quot; + event.fault.faultDetail + &quot;\n&quot; +
					&quot;faultCode: &quot; + event.fault.faultCode, &quot;Error&quot;);
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:RemoteObject id=&quot;testService&quot; destination=&quot;testService&quot; endpoint=&quot;{ENDPOINT}&quot;
		showBusyCursor=&quot;true&quot;/&gt;

	&lt;mx:Button label=&quot;Get remote object&quot; click=&quot;{getRemoteObject()}&quot;/&gt;

&lt;/mx:Application&gt;
</pre>
</div>
<p>In this application, we call a server function named <em>getSentGenericObject</em>. It&#8217;s purpose is simply to send back to the client an object generated dynamically on the server side whose values are the same of the object received in input from the client. As you can see, we create a generic ActionScript object called <em>sentGenericObj</em>, add some properties and send it to the server, then we print on an alert message the values of the object received from the server. Now it&#8217;s time to see how <em>getSentGenericObject</em> is implemented. <span id="more-21"></span></p>
<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.services;

import flex.messaging.io.amf.ASObject;

public class TestService
{
	@SuppressWarnings(&quot;unchecked&quot;)
	public Object getSentGenericObject(ASObject genericObj)
	{
		// Create a new ASObject instance to send to the client with all
		// the properties values received from the client.
		ASObject returnedObj = new ASObject();

		returnedObj.put(&quot;prop1&quot;, genericObj.get(&quot;prop1&quot;));

		ASObject compositeObj = new ASObject();
		returnedObj.put(&quot;composite&quot;, compositeObj);

		compositeObj.put(&quot;sub1&quot;, ((ASObject)genericObj.get(&quot;composite&quot;)).get(&quot;sub1&quot;));
		compositeObj.put(&quot;sub2&quot;, ((ASObject)genericObj.get(&quot;composite&quot;)).get(&quot;sub2&quot;));

		return returnedObj;
	}
}
</pre>
</div>
<p>Since <em>ASObject</em> is in fact an <em>HashMap</em>, all we need to do to generate dynamically an object in Java is add the properties we need as keys of the <em>HashMap</em> and for each property we can assign a value. It&#8217;s really simple. As you can see, we create a new instance of <em>ASObject</em> called <em>returnedObj</em> and add a property named <em>prop1</em> getting its value from the <em>genericObj</em> received from the client. We also create a composite property called <em>composite</em>. With composite I mean a property with sub-properties in it, so <em>composite</em> is another <em>ASObject</em> instance and we can add the sub-properties as we previously did with <em>prop1</em>. This is all we need to do. In this way, we can get a dynamically generated object both on the client and the server side and send it back and forth through BlazeDS. This is the result we get when we click the button on the example application:</p>

<p><img src="http://www.devahead.com/blog/images/BlazeDSASObject/getRemoteObjectResult.jpg"/></p>
<p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2010/04/sending-actionscript-objects-through-blazeds-with-asobject/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Beware of singleton in Flex modules</title>
		<link>http://www.devahead.com/blog/2010/03/beware-of-singleton-in-flex-modules/</link>
		<comments>http://www.devahead.com/blog/2010/03/beware-of-singleton-in-flex-modules/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 23:18:00 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[module]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=18</guid>
		<description><![CDATA[Example 1 (without importing the singleton class in the main application &#8211; module-wide singleton):
Example 2 (singleton class imported in the main application &#8211; application-wide singleton):
This is something I recently discovered during some tests and it&#8217;s something to consider when using the singleton design pattern inside Flex modules. First of all, here is an example implementation [...]]]></description>
			<content:encoded><![CDATA[<p>Example 1 (without importing the singleton class in the main application &#8211; module-wide singleton):<br />
<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/SingletonAndModules01/SingletonAndModules01.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/SingletonAndModules01/srcview/SingletonAndModules01.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div></p>
<p>Example 2 (singleton class imported in the main application &#8211; application-wide singleton):<br />
<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/SingletonAndModules02/SingletonAndModules02.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/SingletonAndModules02/srcview/SingletonAndModules02.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div></p>
<p style="padding-top:10px">This is something I recently discovered during some tests and it&#8217;s something to consider when using the <strong><a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton design pattern</a> inside Flex modules</strong>. First of all, here is an example implementation of the singleton pattern in Flex:</p>
<div class="post-source-code">
<pre class="brush: as3;">
public class SingletonClass
{
	protected static var _instance: SingletonClass = null;

	public static function getInstance(): SingletonClass
	{
		if (_instance == null)
		{
			_instance = new SingletonClass();
		}

		return _instance;
	}
}
</pre>
</div>
<p>This class can be simply used to get the singleton instance with a line like this:</p>
<div class="post-source-code">
<pre class="brush: as3;">
var theInstance: SingletonClass = SingletonClass.getInstance();
</pre>
</div>
<p>This is what we already knew. But what could happen if we try to get a singleton instance inside a Flex module? It could happen that our <em>SingletonClass</em> represents in fact a singleton in two different ways: <strong>application-wide singleton</strong> or <strong>module-wide singleton</strong>. In the application-wide case, the instance of <em>SingletonClass</em> is unique across the entire application that uses some Flex modules, while in the module-wide case, the instance in unique only inside a single module, but different across different modules. This is really important to know because we may have undesired behaviors of our application and it could be difficult to figure out what happens without knowing this.</p>
<p>Now, the question is: <strong>how do we know when we have an application-wide singleton instead of a module-wide singleton?</strong> You may have guessed the answer from the examples links at the beginning of this post. We have an <strong>application-wide when the <em>SingletonClass</em> is imported in the main application</strong> while we have a <strong>module-wide singleton when the <em>SingletonClass</em> is used only inside the modules and never imported in the main application</strong>. An example will be useful to clarify everything. <span id="more-18"></span></p>
<p>To test the <em>SingletonClass</em> instances creation we need to modify a little bit the original class that we saw earlier.</p>
<div class="post-source-code">
<pre class="brush: as3;">
public class SingletonClass
{
	protected static var _instance: SingletonClass = null;

	public static function getInstance(): SingletonClass
	{
		if (_instance == null)
		{
			_instance = new SingletonClass();

			// Generate a random instance ID
			_instance._instanceID = Math.round(Math.random() * 100);
		}

		return _instance;
	}

	protected var _instanceID: Number = NaN;

	public function get instanceID(): Number
	{
		return _instanceID;
	}
}
</pre>
</div>
<p>Each time a new instance of <em>SingletonClass</em> is created, we generate a random ID so we can identify it easily during our tests. A module in the test applications will look like this:</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Module xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			import com.devahead.misc.SingletonClass;

			[Bindable]
			protected var _instance1ID: Number = -1;

			[Bindable]
			protected var _instance2ID: Number = -1;

			protected function onGetInstance1BtnClick(event: MouseEvent): void
			{
				_instance1ID = SingletonClass.getInstance().instanceID;
			}

			protected function onGetInstance2BtnClick(event: MouseEvent): void
			{
				_instance2ID = SingletonClass.getInstance().instanceID;
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:Panel title=&quot;Module 1&quot; layout=&quot;vertical&quot;
		paddingTop=&quot;3&quot; paddingBottom=&quot;3&quot; paddingLeft=&quot;3&quot; paddingRight=&quot;3&quot;&gt;

		&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
			&lt;mx:Button id=&quot;getInstance1Btn&quot; label=&quot;Get instance 1&quot;
				click=&quot;{onGetInstance1BtnClick(event)}&quot;/&gt;

			&lt;mx:Label text=&quot;Instance 1 ID:&quot; fontWeight=&quot;bold&quot;/&gt;
			&lt;mx:Label text=&quot;{_instance1ID}&quot;/&gt;
		&lt;/mx:HBox&gt;

		&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
			&lt;mx:Button id=&quot;getInstance2Btn&quot; label=&quot;Get instance 2&quot;
				click=&quot;{onGetInstance2BtnClick(event)}&quot;/&gt;

			&lt;mx:Label text=&quot;Instance 2 ID:&quot; fontWeight=&quot;bold&quot;/&gt;
			&lt;mx:Label text=&quot;{_instance2ID}&quot;/&gt;
		&lt;/mx:HBox&gt;

	&lt;/mx:Panel&gt;

&lt;/mx:Module&gt;
</pre>
</div>
<p>Here we provide a couple of buttons to invoke two times the <em>getInstance</em> function of the <em>SingletonClass</em> and save the ID of the instance returned by the function. This is simply to show that in fact multiple invocations of the <em>getInstance</em> function return the same instance, so the <em>SingletonClass</em> is working properly.</p>
<p>In the example 1 we don&#8217;t import the <em>SingletonClass</em> so the main application looks very simple:</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Beware of singleton in Flex modules - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;
	viewSourceURL=&quot;srcview/index.html&quot;&gt;

	&lt;mx:Label text=&quot;Push the buttons. The instance ID is different for each module.&quot;/&gt;

	&lt;mx:ModuleLoader url=&quot;com/devahead/modules/Module1.swf&quot;/&gt;
	&lt;mx:ModuleLoader url=&quot;com/devahead/modules/Module2.swf&quot;/&gt;	

&lt;/mx:Application&gt;
</pre>
</div>
<p>To try it, just push the buttons in the different modules and you&#8217;ll see that the IDs of the instances are different. Now let&#8217;s take a look at the example 2. Here we actually do the same thing that we do in the modules, so we use the <em>getInstance</em> function to obtain instances of the <em>SingletonClass</em> hence the type is imported also in the main application.</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Beware of singleton in Flex modules - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;
	viewSourceURL=&quot;srcview/index.html&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			import com.devahead.misc.SingletonClass;

			[Bindable]
			protected var _instance1ID: Number = -1;

			[Bindable]
			protected var _instance2ID: Number = -1;

			protected function onGetInstance1BtnClick(event: MouseEvent): void
			{
				_instance1ID = SingletonClass.getInstance().instanceID;
			}

			protected function onGetInstance2BtnClick(event: MouseEvent): void
			{
				_instance2ID = SingletonClass.getInstance().instanceID;
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:Label text=&quot;Push the buttons. The instance ID is the same for each module and the main application.&quot;/&gt;

	&lt;mx:Panel title=&quot;Main application&quot; layout=&quot;vertical&quot;
		paddingTop=&quot;3&quot; paddingBottom=&quot;3&quot; paddingLeft=&quot;3&quot; paddingRight=&quot;3&quot;&gt;

		&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
			&lt;mx:Button id=&quot;getInstance1Btn&quot; label=&quot;Get instance 1&quot;
				click=&quot;{onGetInstance1BtnClick(event)}&quot;/&gt;

			&lt;mx:Label text=&quot;Instance 1 ID:&quot; fontWeight=&quot;bold&quot;/&gt;
			&lt;mx:Label text=&quot;{_instance1ID}&quot;/&gt;
		&lt;/mx:HBox&gt;

		&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
			&lt;mx:Button id=&quot;getInstance2Btn&quot; label=&quot;Get instance 2&quot;
				click=&quot;{onGetInstance2BtnClick(event)}&quot;/&gt;

			&lt;mx:Label text=&quot;Instance 2 ID:&quot; fontWeight=&quot;bold&quot;/&gt;
			&lt;mx:Label text=&quot;{_instance2ID}&quot;/&gt;
		&lt;/mx:HBox&gt;

	&lt;/mx:Panel&gt;

	&lt;mx:ModuleLoader url=&quot;com/devahead/modules/Module1.swf&quot;/&gt;
	&lt;mx:ModuleLoader url=&quot;com/devahead/modules/Module2.swf&quot;/&gt;	

&lt;/mx:Application&gt;
</pre>
</div>
<p>Pushing all the buttons, you can verify that the instance ID is always the same both in the main application and the modules. This is really important to know every time you work with the singleton pattern and the modules.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2010/03/beware-of-singleton-in-flex-modules/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Reducing Flex compilation time with an assets module</title>
		<link>http://www.devahead.com/blog/2010/02/reducing-flex-compilation-time-with-an-assets-module/</link>
		<comments>http://www.devahead.com/blog/2010/02/reducing-flex-compilation-time-with-an-assets-module/#comments</comments>
		<pubDate>Sun, 28 Feb 2010 21:37:59 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[compilation]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=16</guid>
		<description><![CDATA[Example 1 (normal embeds):
Example 2 (assets module):
Some time ago one of my coworkers pointed me to a blog post that was giving suggestions to reduce the compilation time of a Flex project. Since we had long compilation times for our project at work, I decided to give it a try. The option that I chose [...]]]></description>
			<content:encoded><![CDATA[<p>Example 1 (normal embeds):<br />
<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/EmbeddedAssetsCompilation01/EmbeddedAssetsCompilation01.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/EmbeddedAssetsCompilation01/srcview/EmbeddedAssetsCompilation01.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div></p>
<p>Example 2 (assets module):<br />
<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/EmbeddedAssetsCompilation02/EmbeddedAssetsCompilation02.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/EmbeddedAssetsCompilation02/srcview/EmbeddedAssetsCompilation02.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div></p>
<p style="padding-top:10px">Some time ago one of my coworkers pointed me to a <a href="http://www.rogue-development.com/blog2/2007/11/slow-flex-builder-compile-and-refresh-solution-modules/">blog post</a> that was giving suggestions to <strong>reduce the compilation time of a Flex project</strong>. Since we had long compilation times for our project at work, I decided to give it a try. The option that I chose was <strong>putting all the embeds inside a Flex module</strong> instead of embedding the assets directly inside each single source file. So, before testing the solution on the big project, I prepared a couple of small sample applications to test the difference and see if it was worth trying.</p>
<p>First of all, let&#8217;s briefly talk about the problem. Flex compiler can become slow if it has to embed a lot of assets in the application. This can be an issue if the application is particularly big. It seems that even if you change a single source file, the assets have to be embedded again to recompile everything. So, how can we avoid this? Using an <strong>assets module</strong>, and I&#8217;m going to call this module <em class="highlight">AssetsModule</em> (quite straightforward).</p>
<p>In a standard application, when you want to embed an asset you have something like this:</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Image source=&quot;@Embed(source='assets/myimage.png')&quot;/&gt;
</pre>
</div>
<p>With the usage of an assets module, you will have something like this:</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Image source=&quot;{ModulesManager.getInstance().assets.myimage}&quot;/&gt;
</pre>
</div>
<p>To make our solution work, we need to make sure that there are <strong>no dependencies between the class that contains all the embeds in the module and the normal classes of the application</strong>. An interface is the right choice to achieve our goal.<span id="more-16"></span></p>
<p style="padding-bottom:0">Here are the fundamental components of our solution:</p>
<ul>
<li><strong><em>AssetsModule</em></strong>: the only purpose of this Flex module is to contain all the embedded assets of the application;</li>
<li><strong><em>IAssetsModule</em></strong>: the interface that makes it possible to avoid dependencies between the application and the embedded assets;</li>
<li><strong><em>ModulesManager</em></strong>: this manager class is responsible of loading the <em>AssetsModule</em> and providing access to it through the <em>IAssetsModule</em> interface.</li>
</ul>
<p>The <em>AssetsModule</em> has a really simple structure. It&#8217;s just a collection of embedded assets. For every asset, a getter function is provided so it can be used in the application. We use getter functions instead of simple variables because we are implementing an interface, the <em>IAssetsModule</em> interface, so we must use functions.</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Module xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	implements=&quot;com.devahead.modules.IAssetsModule&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			[Embed(source=&quot;assets/myimage1.png&quot;)]
			protected var _myimage1: Class;
			public function get myimage1(): Class { return _myimage1 };

			[Embed(source=&quot;assets/myimage2.png&quot;)]
			protected var _myimage2: Class;
			public function get myimage2(): Class { return _myimage2 };
		]]&gt;
	&lt;/mx:Script&gt;

&lt;/mx:Module&gt;
</pre>
</div>
<p>The <em>IAssetsModule</em> interface lists all the available assets through a getter function for each one of them.</p>
<div class="post-source-code">
<pre class="brush: as3;">
package com.devahead.modules
{
	public interface IAssetsModule
	{
		function get myimage1(): Class;
		function get myimage2(): Class;
	}
}
</pre>
</div>
<p>Now it&#8217;s time to take a look at the <em>ModulesManager</em> class. Since the assets are shared across all the classes of the application, it&#8217;s a singleton. So we have a <em>getInstance</em> method that creates an instance of the modules manager, if it has not already been created, then loads the module. The application&#8217;s classes can access the assets through the <em>assets</em> instance property of the modules manager. That property can also be used in curly brackets because it&#8217;s bindable and an event (<em>assetsModuleChanged</em>) is dispatched as soon as the module has been fully loaded.</p>
<div class="post-source-code">
<pre class="brush: as3;">
package com.devahead.modules
{
	import flash.events.Event;
	import flash.events.EventDispatcher;

	import mx.controls.Alert;
	import mx.events.ModuleEvent;
	import mx.modules.ModuleLoader;

	public class ModulesManager extends EventDispatcher
	{
		protected static var _instance: ModulesManager = null;

		public static function getInstance(): ModulesManager
		{
			if (_instance == null)
			{
				_instance = new ModulesManager();

				_instance.loadAssetsModule();
			}

			return _instance;
		}

		protected var _assets: IAssetsModule = null;

		[Bindable(&quot;assetsModuleChanged&quot;)]
		public function get assets(): IAssetsModule
		{
			return _assets;
		}

		protected var _assetsModuleLoader: ModuleLoader = null;

		protected function loadAssetsModule(): void
		{
			if (_assetsModuleLoader == null)
			{
				_assetsModuleLoader = new ModuleLoader();
				_assetsModuleLoader.addEventListener(ModuleEvent.READY, onAssetsModuleReady);
				_assetsModuleLoader.addEventListener(ModuleEvent.ERROR, onAssetsModuleError);
				_assetsModuleLoader.loadModule(&quot;com/devahead/modules/AssetsModule.swf&quot;);
			}
		}

		protected function onAssetsModuleReady(event: ModuleEvent): void
		{
			_assets = (_assetsModuleLoader.child as IAssetsModule);

			dispatchEvent(new Event(&quot;assetsModuleChanged&quot;));
		}

		protected function onAssetsModuleError(event: ModuleEvent): void
		{
			Alert.show(&quot;Error while loading AssetsModule.\n\n&quot; + event.errorText, &quot;Error&quot;);
		}
	}
}
</pre>
</div>
<p>Now you might be curious about the <strong>compilation performance improvements</strong> that we get using this solution. To test it, I made a simple application in two different versions, one with the assets module and one with the standard embeds spread all over the application&#8217;s classes. In each version, the application is always made up of 100 components and each of them uses 100 images. The difference is how the images are used. I&#8217;m not going to write the example source code here since you can download it through the link provided at the beginning of this post and since it&#8217;s quite repetitive, instead here I&#8217;m going to give the different performance results that I got using the described technique.</p>
<p>Here are the performance results with the example application:</p>
<table>
<tr>
<th>&nbsp;</th>
<th>With clean (m:ss)</th>
<th>Without clean (m:ss)</th>
</tr>
<tr>
<td>Normal embeds</td>
<td align="right">1:34</td>
<td align="right">0:54</td>
</tr>
<tr>
<td>With <em>AssetsModule</em></td>
<td align="right">0:45</td>
<td align="right">0:07</td>
</tr>
</table>
<p style="padding-top:15px"><em>With clean</em> means that the application has been built after cleaning the project in Eclipse (i.e. from scratch), while <em>without clean</em> means that I added only a space character in the main application mxml file and then built the project without cleaning it first. As you can see with the test projects, the difference is quite evident, especially when the <em>AssetsModule</em> doesn&#8217;t need to be rebuilt because we don&#8217;t need to clean the project. In that case, the assets don&#8217;t have to be embedded again and this allows to compile only the application&#8217;s classes.</p>
<p>Another important fact to note is that in the test project, the number of different embedded images is 100. With the normal embeds the same 100 images are embedded in each one of the 100 components used by the main file, while with the assets module, the 100 images are embedded only one time for all the different components. This means that with the <em>AssetsModule</em> <strong>we reduced the number of embeds from 1000 to 100</strong> because we are reusing the same embedded asset across multiple application&#8217;s classes without needing to embed it again for each one of them.</p>
<p>At this point you could say: OK, it works great with the example application, but how does it work in a real world scenario? Since at the beginning of the post I wrote that I started looking into this subject because of the long compilation times we had for our project at work, I&#8217;ll show you some results that I got on that real project. It&#8217;s a big one (about 900 Flex source files, excluding external libraries). We use a few modules so the compilation times are still high also after refactoring it with the solution I described here, but let the numbers speak for themselves.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>With clean (m:ss)</th>
<th>Without clean (m:ss)</th>
</tr>
<tr>
<td>Normal embeds</td>
<td align="right">7:58</td>
<td align="right">1:07</td>
</tr>
<tr>
<td>With <em>AssetsModule</em></td>
<td align="right">7:09</td>
<td align="right">0:58</td>
</tr>
</table>
<p style="padding-top:15px">As you can see, we had an improvement, but the compilation time without cleaning the project wasn&#8217;t reduced much. This could be due to the project specific dependencies tree and complexity. Anyway, we had a reduction of compilation time with the clean. Note that with the <em>AssetsModule</em> the number of embeds became 280, while before the refactoring we had 977 embeds.</p>
<p>Now it&#8217;s time to talk about the conclusions. This is my opinion after trying all of this. Using an assets module is potentially very convenient to reduce the compilation time, but it depends on the specific project. When you&#8217;re compiling the project from scratch, the improvements should be noticeable. Anyway, using an <em>AssetsModule</em> is convenient also because you&#8217;re organizing well all the assets of you application, avoiding duplicate embeds and having a single central location for all of them. So, I would suggest to <strong>always use an assets module since the beginning</strong> to avoid potential compilation performance problems in the future. What seems sure is that you&#8217;ve got nothing to loose.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2010/02/reducing-flex-compilation-time-with-an-assets-module/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Filtering the children of a Flex container</title>
		<link>http://www.devahead.com/blog/2010/01/filtering-the-children-of-a-flex-container/</link>
		<comments>http://www.devahead.com/blog/2010/01/filtering-the-children-of-a-flex-container/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 16:57:48 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[children]]></category>
		<category><![CDATA[container]]></category>
		<category><![CDATA[filter]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=14</guid>
		<description><![CDATA[In this post I&#8217;m going to show an utility function that I implemented some time ago. Its purpose is to filter the children of a Flex container. So, for example, let&#8217;s say that you want to have all the children of a specific container going deep throughout the entire children hierarchy, but you want to [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/FilterContainerChildren/FilterContainerChildren.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/FilterContainerChildren/srcview/FilterContainerChildren.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p>In this post I&#8217;m going to show an utility function that I implemented some time ago. Its purpose is to filter the children of a Flex container. So, for example, let&#8217;s say that you want to have all the children of a specific container going deep throughout the entire children hierarchy, but you want to exclude some classes or instances from the search, then this function is for you. I use it to selectively enable or disable some components or to get the value of a specific property for them, but the function is generic enough to be used in many different situations.</p>
<p>The function is called <em class="highlight">getContainerChildren</em>. Here is its source code:</p>
<div class="post-source-code">
<pre class="brush: as3;">
package com.devahead.utils
{
	import mx.collections.ArrayCollection;
	import mx.core.Container;

	public class MiscUtils
	{
		/**
		 * Filters all the children of a container.
		 *
		 * @param container
		 *         Container of the children that have to be filtered.
		 * @param childrenClasses
		 *         Array of the classes that have to be kept while
		 *         filtering the children. If not specified, the type
		 *         of the children is not considered while filtering.
		 * @param excludedClasses
		 *         Array of the classes that have to be excluded.
		 *         The children must not belong to these types.
		 * @param excludedInstances
		 *         Array of the instances that have to be excluded.
		 *         The children must not be one of these instances.
		 * @param deepSearch
		 *         If true, specifies that the children must be
		 *         searched throughout the entire hierarchy util
		 *         there are no more children available for a
		 *         component. If false, only the children of the
		 *         container are considered and not their children.
		 * @param forceDeepSearchOnExcludedClasses
		 *         If true and also deepSearch is true, then the children
		 *         are searched also within the components that have been
		 *         excluded from the results because their type is among
		 *         the excludedClasses. If false, the children are never
		 *         searched within the excluded components. If a component
		 *         has been excluded because it's in excludedInstances, then
		 *         a deep search is never executed on it, even if it belongs
		 *         to an excluded class and forceDeepSearchOnExcludedClasses
		 *         is true.
		 * @param forceDeepSearchOnExcludedInstances
		 *         If true and also deepSearch is true, then the children
		 *         are searched also within the components that have been
		 *         excluded from the results because they are among
		 *         the excludedInstances. If false, the children are never
		 *         searched within the excluded components.
		 * @param resultArray
		 *         Array used to store the children found in the recursive
		 *         calls. It should be left null when the function is called
		 *         externally (not recursively).
		 * @return Array of the container's children filtered according
		 *         to the specified parameters.
		 */
		public static function getContainerChildren(container: Container,
			childrenClasses: Array = null, excludedClasses: Array = null,
			excludedInstances: Array = null, deepSearch: Boolean = false,
			forceDeepSearchOnExcludedClasses: Boolean = false,
			forceDeepSearchOnExcludedInstances: Boolean = false,
			resultArray: ArrayCollection = null): ArrayCollection
		{
			var componentsArray: ArrayCollection = (resultArray != null ?
				resultArray : new ArrayCollection());

			if (container != null)
			{
				// Check all the container's children
				for (var i: int = 0; i &lt; container.numChildren; i++)
				{
					var currChild: Object = container.getChildAt(i);

					var isCorrectComponent: Boolean = false;

					// Check if the type of the current child is correct
					if (childrenClasses == null || childrenClasses.length == 0)
					{
						isCorrectComponent = true;
					}
					else
					{
						for each (var currClass: Class in childrenClasses)
						{
							if (currChild is currClass)
							{
								isCorrectComponent = true;
								break;
							}
						}
					}

					// Check if the current child is an instance that has to be excluded
					var excludedAsInstance: Boolean = false;

					if (excludedInstances != null &amp;&amp; excludedInstances.length &gt; 0)
					{
						for each (var currExcInst: Object in excludedInstances)
						{
							if (currChild == currExcInst)
							{
								isCorrectComponent = false;
								excludedAsInstance = true;
								break;
							}
						}
					}

					// Check if the current child's type has to be excluded
					var excludedAsClass: Boolean = false;

					if (excludedClasses != null &amp;&amp; excludedClasses.length &gt; 0)
					{
						for each (var currExcClass: Class in excludedClasses)
						{
							if (currChild is currExcClass)
							{
								isCorrectComponent = false;
								excludedAsClass = true;
								break;
							}
						}
					}

					// Check if I must use a deep search
					var mustGoDeeper: Boolean = (
						(excludedAsInstance &amp;&amp; forceDeepSearchOnExcludedInstances) ||
						(!excludedAsInstance &amp;&amp; excludedAsClass &amp;&amp; forceDeepSearchOnExcludedClasses));

					if (deepSearch &amp;&amp; (currChild is Container) &amp;&amp;
						((!excludedAsInstance &amp;&amp; !excludedAsClass) || mustGoDeeper))
					{
						// Get all the children of the current child through a recursive call.
						//
						// NOTE: I don't need to care about the result value of the recursive
						//       call because the children found are directly inserted into the
						//       componentsArray variable.
						getContainerChildren(currChild as Container, childrenClasses,
							excludedClasses, excludedInstances, deepSearch,
							forceDeepSearchOnExcludedClasses, forceDeepSearchOnExcludedInstances,
							componentsArray);
					}

					if (isCorrectComponent)
					{
						// Add the child to the result list
						componentsArray.addItem(currChild);
					}
				}
			}

			return componentsArray;
		}
	}
}
</pre>
</div>
<p>The function is recursive, so during every recursion all the children of a container are discovered and they are filtered according to the specified exclusion classes or instances. If we must go deeper to find other components, then another recursion step is executed.<span id="more-14"></span></p>
<p>Here is an example application. It shows some different ways to use the filtering function. For each filter, there are a button and a label next to it showing the parameters of the function. When a button is pressed, all the resulting components are written in the text area under the buttons. For each component you can see its ID and the path in the hierarchy to reach it.</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Filtering the children of a Flex container - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;
	viewSourceURL=&quot;srcview/index.html&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			import mx.core.Container;
			import com.devahead.utils.MiscUtils;
			import mx.core.UIComponent;
			import mx.collections.ArrayCollection;

			protected function printResult(result: ArrayCollection): void
			{
				resultArea.text = &quot;&quot;;

				if (result != null &amp;&amp; result.length &gt; 0)
				{
					for each (var item: UIComponent in result)
					{
						resultArea.text += item.id + &quot; (&quot; + item.toString() + &quot;)\n&quot;;
					}
				}
			}

			protected function getAllTextInput(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, [TextInput], null, null, true));
			}

			protected function getAllComboBox(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, [ComboBox], null, null, true));
			}

			protected function getAllLabel(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, [Label], null, null, true));
			}

			protected function getAllTextInputNotVbox1(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, [TextInput],
					null, [vbox1], true));
			}

			protected function getAllComboBoxNotPanel(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, [ComboBox],
					[Panel], null, true));
			}

			protected function getAllUIComponentNotComboBox(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, [UIComponent],
					[ComboBox], null, true));
			}

			protected function getAllNotVbox1OKChildren(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, null,
					null, [vbox1], true, false, true));
			}

			protected function getAllNotPanelVBoxOKChildren(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, null,
					[Panel, VBox], null, true, true));
			}

			protected function getTextInputOnlyInVbox1(): void
			{
				printResult(MiscUtils.getContainerChildren(vbox1, [TextInput]));
			}

			protected function getTextInputOnlyInPan1(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, [TextInput]));
			}

			protected function getAllPan1(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1));
			}

			protected function getAllPan1DeepSearch(): void
			{
				printResult(MiscUtils.getContainerChildren(pan1, null, null, null, true));
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:HBox&gt;
		&lt;mx:Panel id=&quot;pan1&quot; title=&quot;pan1&quot;&gt;
			&lt;mx:VBox id=&quot;vbox1&quot; backgroundAlpha=&quot;0.2&quot; backgroundColor=&quot;0xff0000&quot;&gt;
				&lt;mx:TextInput id=&quot;text1&quot; text=&quot;text1 in vbox1&quot;/&gt;
				&lt;mx:TextInput id=&quot;text2&quot; text=&quot;text2 in vbox1&quot;/&gt;
				&lt;mx:ComboBox id=&quot;combo1&quot; prompt=&quot;combo1 in vbox1&quot;/&gt;
			&lt;/mx:VBox&gt;

			&lt;mx:TextInput id=&quot;text3&quot; text=&quot;text3&quot;/&gt;
			&lt;mx:Label id=&quot;lab1&quot; text=&quot;lab1&quot;/&gt;

			&lt;mx:Panel id=&quot;pan2&quot; title=&quot;pan2&quot;&gt;
				&lt;mx:Label id=&quot;lab2&quot; text=&quot;lab2 in pan2&quot;/&gt;
				&lt;mx:ComboBox id=&quot;combo2&quot; prompt=&quot;combo2 in pan2&quot;/&gt;
			&lt;/mx:Panel&gt;
		&lt;/mx:Panel&gt;

		&lt;mx:Box backgroundColor=&quot;0xffffff&quot; backgroundAlpha=&quot;0.5&quot; height=&quot;100%&quot;&gt;
			&lt;mx:Text fontSize=&quot;12&quot;&gt;
				&lt;mx:htmlText&gt;
					&lt;![CDATA[
&lt;i&gt;getContainerChildren&lt;/i&gt;(
  container: &lt;b&gt;Container&lt;/b&gt;,
  childrenClasses: &lt;b&gt;Array&lt;/b&gt; = null,
  excludedClasses: &lt;b&gt;Array&lt;/b&gt; = null,
  excludedInstances: &lt;b&gt;Array&lt;/b&gt; = null,
  deepSearch: &lt;b&gt;Boolean&lt;/b&gt; = false,
  forceDeepSearchOnExcludedClasses: &lt;b&gt;Boolean&lt;/b&gt; = false,
  forceDeepSearchOnExcludedInstances: &lt;b&gt;Boolean&lt;/b&gt; = false,
  resultArray: &lt;b&gt;ArrayCollection&lt;/b&gt; = null): &lt;b&gt;ArrayCollection&lt;/b&gt;
				]]&gt;
				&lt;/mx:htmlText&gt;
			&lt;/mx:Text&gt;
		&lt;/mx:Box&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:Spacer height=&quot;20&quot;/&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all TextInput&quot; click=&quot;{getAllTextInput()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, [TextInput], null, null, true)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all ComboBox&quot; click=&quot;{getAllComboBox()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, [ComboBox], null, null, true)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all Label&quot; click=&quot;{getAllLabel()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, [Label], null, null, true)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all TextInput but not those in vbox1&quot;
			click=&quot;{getAllTextInputNotVbox1()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, [TextInput], null, [vbox1], true)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all ComboBox but not those children of a Panel&quot;
			click=&quot;{getAllComboBoxNotPanel()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, [ComboBox], [Panel], null, true)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all UIComponent but not the instances of ComboBox&quot;
			click=&quot;{getAllUIComponentNotComboBox()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, [UIComponent], [ComboBox], null, true)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all components, exclude vbox1, but get its children&quot;
			click=&quot;{getAllNotVbox1OKChildren()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, null, null, [vbox1], true, false, true)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all components, exclude Panel and VBox, but get their children&quot;
			click=&quot;{getAllNotPanelVBoxOKChildren()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, null, [Panel, VBox], null, true, true)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get TextInput only if children of vbox1&quot;
			click=&quot;{getTextInputOnlyInVbox1()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(vbox1, [TextInput])&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get TextInput only if children of pan1&quot;
			click=&quot;{getTextInputOnlyInPan1()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, [TextInput])&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all the children of pan1&quot; click=&quot;{getAllPan1()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox verticalAlign=&quot;middle&quot;&gt;
		&lt;mx:Button label=&quot;Get all the children of pan1 (deep search)&quot;
			click=&quot;{getAllPan1DeepSearch()}&quot;/&gt;
		&lt;mx:Label text=&quot;getContainerChildren(pan1, null, null, null, true)&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:Spacer height=&quot;20&quot;/&gt;

	&lt;mx:Label text=&quot;Result:&quot;/&gt;
	&lt;mx:TextArea id=&quot;resultArea&quot; width=&quot;450&quot; height=&quot;200&quot; wordWrap=&quot;false&quot;/&gt;
&lt;/mx:Application&gt;
</pre>
</div>
<p>I&#8217;m not going to explain each different usage because the function is really generic, so it&#8217;s up to you to decide if it suits your needs or not. I just hope it helps somebody.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2010/01/filtering-the-children-of-a-flex-container/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting all the popups in a Flex application</title>
		<link>http://www.devahead.com/blog/2009/12/getting-all-the-popups-in-a-flex-application/</link>
		<comments>http://www.devahead.com/blog/2009/12/getting-all-the-popups-in-a-flex-application/#comments</comments>
		<pubDate>Sat, 19 Dec 2009 16:32:13 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[popup]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=11</guid>
		<description><![CDATA[In Flex, you can create popups easily, but what if you want to get all of them after they&#8217;ve already been created? You could keep track of every created popup using a customized function that puts every single instance in an array for example, but what if you&#8217;re using a Flex component that simply creates [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/GetAllPopups/GetAllPopups.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/GetAllPopups/srcview/GetAllPopups.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p>In Flex, you can create popups easily, but what if you want to get all of them after they&#8217;ve already been created? You could keep track of every created popup using a customized function that puts every single instance in an array for example, but what if you&#8217;re using a Flex component that simply creates popups in its own way and you cannot keep track of what it creates? Here I&#8217;m going to provide a possible solution.</p>
<p>After some debugging, I found out that <strong>Flex puts all the popups among the <em>rawChildren</em> in the application&#8217;s <em>SystemManager</em>.</strong> This is where we can find them. So now that we know where to look, we need a way to distinguish the children that are popups from those that are not (<em>rawChildren</em> does not contain only popups). If we use only components whose base class is the standard <em>UIComponent</em> class (I think this is the case most of the times), <strong>there&#8217;s an easy way to know if an instance is a popup or not: the <em>isPopUp</em> property of <em>UIComponent</em></strong>.</p>
<p>Whenever we create a new popup that extends <em>UIComponent</em>, the <em>PopUpManager</em> sets the <em>isPopUp</em> property to <em>true</em>. So, all we need to do is cycle through the application&#8217;s <em>systemManager.rawChildren</em> and check whether we find an <em>UIComponent</em> instance whose <em>isPopUp</em> property is <em>true</em>. In that case, we&#8217;ve got an application&#8217;s popup.</p>
<p>To demonstrate the concept, I&#8217;ve implemented the <em class="highlight">PopUpUtils</em> class. It simply allows you to get all the popups inside an application instance, to discover if there are visible popups and to close all the popups. Let&#8217;s take a look at it.<span id="more-11"></span></p>
<div class="post-source-code">
<pre class="brush: as3;">
package com.devahead.utils
{
	import flash.display.DisplayObject;

	import mx.collections.ArrayCollection;
	import mx.core.Application;
	import mx.core.IChildList;
	import mx.core.UIComponent;
	import mx.managers.PopUpManager;

	public class PopUpUtils
	{
		/**
		 * Returns all the popups inside an application. Only the popups whose base
		 * class is UIComponent are returned.
		 *
		 * @param applicationInstance
		 *   Application instance. If null, Application.application is used.
		 * @param onlyVisible
		 *   If true, considers only the visible popups.
		 * @return All the popups in the specified application.
		 */
		public static function getAllPopups(applicationInstance: Object = null,
			onlyVisible: Boolean = false): ArrayCollection
		{
			var result: ArrayCollection = new ArrayCollection();

			if (applicationInstance == null)
			{
				applicationInstance = Application.application;
			}

			var rawChildren: IChildList = applicationInstance.systemManager.rawChildren;

			for (var i: int = 0; i &lt; rawChildren.numChildren; i++)
			{
				var currRawChild: DisplayObject = rawChildren.getChildAt(i);

				if ((currRawChild is UIComponent) &amp;&amp; UIComponent(currRawChild).isPopUp)
				{
					if (!onlyVisible || UIComponent(currRawChild).visible)
					{
						result.addItem(currRawChild);
					}
				}
			}

			return result;
		}

		/**
		 * Checks if an application has visible popups. Only the popups whose base
		 * class is UIComponent are considered.
		 *
		 * @param applicationInstance
		 *   Application instance. If null, Application.application is used.
		 * @return True if there are visible popups in the specified application,
		 *         false otherwise.
		 */
		public static function hasVisiblePopups(applicationInstance: Object = null): Boolean
		{
			if (applicationInstance == null)
			{
				applicationInstance = Application.application;
			}

			var rawChildren: IChildList = applicationInstance.systemManager.rawChildren;

			for (var i: int = 0; i &lt; rawChildren.numChildren; i++)
			{
				var currRawChild: DisplayObject = rawChildren.getChildAt(i);

				if ((currRawChild is UIComponent) &amp;&amp; UIComponent(currRawChild).isPopUp
					&amp;&amp; UIComponent(currRawChild).visible)
				{
					return true;
				}
			}

			return false;
		}

		/**
		 * Closes all the popups belonging to an application. Only the popups
		 * whose base class is UIComponent are considered.
		 *
		 * @param applicationInstance
		 *   Application instance. If null, Application.application is used.
		 * @return The list of the closed popups.
		 */
		public static function closeAllPopups(applicationInstance: Object = null): ArrayCollection
		{
			var allPopups: ArrayCollection = getAllPopups(applicationInstance);

			for each (var currPopup: UIComponent in allPopups)
			{
				PopUpManager.removePopUp(currPopup);
			}

			return allPopups;
		}
	}
}
</pre>
</div>
<p>As you can see, the <em>getAllPopups</em> function returns all the popups inside an appplication instance. If the instance is not specified, then the current application is used (the one in which the function is called). The <em>hasVisiblePopups</em> is basically the same, except the fact that it stops executing as soon as a visible popup is found. The <em>closeAllPopups</em> function closes all the popups in the application.</p>
<p>Here is an example on how the <em>PopUpUtils</em> class can be used.</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Getting all the popups in a Flex application - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;
	applicationComplete=&quot;{onApplicationComplete(event)}&quot;
	viewSourceURL=&quot;srcview/index.html&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			import mx.controls.Alert;
			import mx.core.UIComponent;
			import mx.collections.ArrayCollection;
			import com.devahead.utils.PopUpUtils;
			import mx.core.IFlexDisplayObject;
			import mx.containers.Panel;
			import mx.managers.PopUpManager;
			import mx.events.FlexEvent;

			protected var counter: int = 1;

			protected function onApplicationComplete(event: FlexEvent): void
			{
				// Add 10 popups on startup
				for (var i: int = 0; i &lt; 10; i++)
				{
					addPopUp();
				}
			}

			protected function addPopUp(): void
			{
				// Create a Panel popup setting a random position for it

				const X_OFFSET: int = 200;

				var popup: IFlexDisplayObject = PopUpManager.createPopUp(this, Panel);

				popup.width = 200;
				popup.height = 200;

				popup.x = X_OFFSET + (Math.random() * (width - X_OFFSET - popup.width));
				popup.y = Math.random() * (height - popup.height);

				(popup as Panel).title = &quot;PopUp &quot; + (counter++);
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:Button label=&quot;Add popup&quot; click=&quot;{addPopUp()}&quot;/&gt;
	&lt;mx:Button label=&quot;Are there visible popups?&quot;
		click=&quot;{Alert.show(PopUpUtils.hasVisiblePopups() ? 'Yes' : 'No',
			'Are there visible popups?')}&quot;/&gt;
	&lt;mx:Button label=&quot;Close all popups&quot; click=&quot;{PopUpUtils.closeAllPopups()}&quot;/&gt;

&lt;/mx:Application&gt;
</pre>
</div>
<p>The example application creates 10 popups on startup, then you can create additional popups, you can check if there are visible popups or you can close them all. I used a standard <em>Panel</em> to create popups instances. The <em>X_OFFSET</em> is useful only to avoid having the popups over the buttons, just for usability.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2009/12/getting-all-the-popups-in-a-flex-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic ObjectProxy</title>
		<link>http://www.devahead.com/blog/2009/12/dynamic-objectproxy/</link>
		<comments>http://www.devahead.com/blog/2009/12/dynamic-objectproxy/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 17:07:25 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[ObjectProxy]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=9</guid>
		<description><![CDATA[The problem: I&#8217;ve got a Flex class with all its properties well defined. It&#8217;s good for me, it has all the properties I need to represent correctly the model, but sometimes I wish I had a few more properties to use it in some contexts. These additional properties are not strictly related to the model [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/DynamicObjectProxy/DynamicObjectProxy.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/DynamicObjectProxy/srcview/DynamicObjectProxy.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p><strong>The problem:</strong> I&#8217;ve got a Flex class with all its properties well defined. It&#8217;s good for me, it has all the properties I need to represent correctly the model, but sometimes I wish I had a few more properties to use it in some contexts. These additional properties are not strictly related to the model I want to represent, so I don&#8217;t want to add them to the class, but I need them to easily integrate with Flex components functionalities for user interaction.</p>
<p><strong>The solution:</strong> <em class="highlight">DynaObjectProxy</em>!</p>
<p>Before looking through the source code of <em>DynaObjectProxy</em>, let&#8217;s talk briefly about what it does. Basically, it&#8217;s a sort of <em>ObjectProxy</em>, but it extends its functionalities.</p>
<p>With <em>ObjectProxy</em> you can <strong>wrap a class instance</strong> and access to its properties through the proxy</p>
<div class="post-source-code">
<pre class="brush: as3;">
// MyClass contains the property &quot;prop1&quot;
var myClassInstance: MyClass = new MyClass();
myClassInstance.prop1 = &quot;The value&quot;;

var myProxy: ObjectProxy = new ObjectProxy(myClassInstance);

trace(myProxy.prop1); // Outputs &quot;The value&quot;
</pre>
</div>
<p>but you <strong>cannot dynamically create new properties</strong> in the <em>ObjectProxy</em> instance</p>
<div class="post-source-code">
<pre class="brush: as3;">
trace(myProxy.prop2); // ERROR! &quot;prop2&quot; doesn't exist in MyClass
</pre>
</div>
<p>Otherwise, you can create an <em>ObjectProxy</em> instance <strong>without wrapping a class instance</strong> and in this case you actually <strong>can create new properties</strong> in the <em>ObjectProxy</em></p>
<div class="post-source-code">
<pre class="brush: as3;">
var myProxy: ObjectProxy = new ObjectProxy();
myProxy.prop2 = &quot;The property value&quot;;

trace(myProxy.prop2); // Outputs &quot;The property value&quot;
</pre>
</div>
<p>What if I would like to have both the functionalities? <em>DynaObjectProxy</em> allows exactly this: you can <strong>both wrap a class instance and create new properties</strong> keeping all the new properties bindable at the same time.</p>
<p>Now we can start looking through the <em>DynaObjectProxy</em> source code and later we&#8217;ll see how it can be used with an example.<span id="more-9"></span></p>
<div class="post-source-code">
<pre class="brush: as3;">package com.devahead.utils
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.Proxy;
	import flash.utils.describeType;
	import flash.utils.flash_proxy;
	import flash.utils.getQualifiedClassName;

	import mx.events.PropertyChangeEvent;
	import mx.utils.ObjectProxy;

	[Bindable(&quot;propertyChange&quot;)]
	public dynamic class DynaObjectProxy extends Proxy implements IEventDispatcher
	{
		/**
		 * EventDispatcher used by the proxy to dispatch events.
		 */
		protected var _dispatcher: EventDispatcher;

		/**
		 * Object managed by the proxy.
		 */
		protected var _managedObj: Object = null;

		/**
		 * ObjectProxy used to managed the _managedObj.
		 */
		protected var _managedObjProxy: ObjectProxy = null;

		/**
		 * ObjectProxy used to allow the dynamic creation of
		 * new bindable properties.
		 */
		protected var _dynamicObjProxy: ObjectProxy = null;

		/**
		 * List of the properties belonging to the proxy. It contains, in
		 * alphabetical order, the list of all the properties beloging to
		 * the _managedObj plus those created dynamically on the _dynamicObjProxy.
		 */
		protected var _propertyList: Array = null;

		/**
		 * Constructor.
		 *
		 * @param managedObj
		 *         Object managed by the proxy.
		 */
		public function DynaObjectProxy(managedObj: Object = null)
		{
			super();

			_managedObj = managedObj;

			_propertyList = new Array();

			// Create the ObjectProxy to manage the managedObj and the one to manage
			// the dynamically created properties.
			_managedObjProxy = (managedObj != null ?
				new ObjectProxy(managedObj) :
				new ObjectProxy());

			_dynamicObjProxy = new ObjectProxy();

			// Create the events dispatcher and attach the appropriate listeners
			// to both the ObjectProxy.
			_dispatcher = new EventDispatcher(this);
			_managedObjProxy.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onPropertyChangeEvent);
			_dynamicObjProxy.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onPropertyChangeEvent);
		}

		/**
		 * Returns all the properties beloging to an object.
		 *
		 * @param obj
		 *         Object.
		 * @return All the object's properties.
		 */
		public static function getObjectProperties(obj: Object): Array
		{
			var result: Array = new Array();

			var objClassInfo: XML = describeType(obj);

			for each (var v: XML in objClassInfo..accessor)
			{
				result.push(String(v.@name));
			}

			return result;
		}

		/**
		 * Returns the original instance of the object managed internally
		 * by the proxy.
		 */
		public function get managedObj(): Object
		{
			return _managedObj;
		}

		/**
		 * Update the list of all the properties available in the proxy (those
		 * visible from outside the proxy by its users).
		 * The list contains, in alphabetical order, the set of the properties
		 * in the managedObj and those in the dynamicObj.
		 */
		protected function updatePropertyList(): void
		{
			var newPropertyList: Array = new Array();

			if (_managedObj != null)
			{
				if (getQualifiedClassName(_managedObj) == &quot;Object&quot;)
				{
					// This is an Object so I can get all of its properties
					// through a cycle.
					for (var managedPropName: String in _managedObj)
					{
						newPropertyList.push(managedPropName);
					}
				}
				else
				{
					// This is likely to be a typed object so I get all its properties
					// through the getObjectProperties function.
					newPropertyList = getObjectProperties(_managedObj);
				}
			}

			// Add to the list also the properties created dynamically in the
			// dynamicObj.
			for (var dynamicPropName: String in _dynamicObjProxy)
			{
				newPropertyList.push(dynamicPropName);
			}

			// Update the _propertyList and sort it in alphabetical order.
			_propertyList = newPropertyList;
			_propertyList.sort();
		}

		/**
		 * Handler for the properties changes in the managedObj and the dynamicObj.
		 * This function dispatches again the PropertyChangeEvent as if it was
		 * generated by this proxy instead of the internal ObjectProxy used for
		 * managedObj and dynamicObj.
		 *
		 * @param event
		 *         Event.
		 */
		protected function onPropertyChangeEvent(event: PropertyChangeEvent): void
		{
			var newEvent: PropertyChangeEvent = new PropertyChangeEvent(event.type,
				event.bubbles, event.cancelable, event.kind, event.property,
				event.oldValue, event.newValue, this);

			dispatchEvent(newEvent);
		}

		// *** Implementation of Proxy methods ***

		override flash_proxy function getProperty(name: *): *
		{
			// If the property is in the managedObj then I return its value,
			// otherwise I use property's value from the dynamicObj.
			return (_managedObjProxy.hasOwnProperty(name) ?
				_managedObjProxy[name] :
				_dynamicObjProxy[name]);
		}

		override flash_proxy function callProperty(name: *, ... rest): *
		{
			// If the function is in the managedObj then I call it,
			// otherwise I call the function in the dynamicObj.
			return (_managedObjProxy.hasOwnProperty(name) ?
				_managedObjProxy[name].apply(_managedObjProxy, rest) :
				_dynamicObjProxy[name].apply(_dynamicObjProxy, rest));
		}

		override flash_proxy function deleteProperty(name: *): Boolean
		{
			// I cannot delete a property from the managedObj, so I delete it directly
			// from the dynamicObj.
			return (_dynamicObjProxy.hasOwnProperty(name) ?
				delete _dynamicObjProxy[name] : false);
		}

		override flash_proxy function hasProperty(name: *): Boolean
		{
			// A property exists if it's inside the managedObj or the dynamicObj
			return (_managedObjProxy.hasOwnProperty(name) ||
				_dynamicObjProxy.hasOwnProperty(name));
		}

		override flash_proxy function nextName(index: int): String
		{
			return _propertyList[index - 1];
		}

		override flash_proxy function nextNameIndex(index: int): int
		{
			if (index == 0)
			{
				// I update the list of alla the properties available in the proxy,
				// those from the managedObj and those dynamically created in the
				// dynamicObj.
				updatePropertyList();
			}

			if (index &lt; _propertyList.length)
			{
				return index + 1;
			}
			else
			{
				return 0;
			}
		}

		override flash_proxy function nextValue(index: int): *
		{
			return flash_proxy::getProperty(_propertyList[index - 1]);
		}

		override flash_proxy function setProperty(name: *, value: *): void
		{
			// If the property is in the managedObj then I set its value, otherwise
			// I set the value on the dynamicObj (the property is created if it
			// doesn't already exist).
			if (_managedObjProxy.hasOwnProperty(name))
			{
				_managedObjProxy[name] = value;
			}
			else
			{
				_dynamicObjProxy[name] = value;
			}
		}

		// *** IEventDispatcher implementation ***

		public function addEventListener(type: String, listener: Function,
			useCapture: Boolean = false, priority: int = 0,
			useWeakReference: Boolean = false): void
		{
			_dispatcher.addEventListener(type, listener, useCapture, priority,
				useWeakReference);
		}

		public function removeEventListener(type: String, listener: Function,
			useCapture: Boolean = false): void
		{
			_dispatcher.removeEventListener(type, listener, useCapture);
		}

		public function dispatchEvent(event: Event): Boolean
		{
			return _dispatcher.dispatchEvent(event);
		}

		public function hasEventListener(type: String): Boolean
		{
			return _dispatcher.hasEventListener(type);
		}

		public function willTrigger(type: String): Boolean
		{
			return _dispatcher.willTrigger(type);
		}
	}
}</pre>
</div>
<p>The constructor accepts a <em class="highlight">managedObj</em> argument. That&#8217;s the class instance that can be wrapped by the proxy and we call it the <em class="highlight">managed object</em>. Internally, two different proxies are created, the <em class="highlight">managedObjProxy</em> and the <em class="highlight">dynamicObjProxy</em>. The first one is useful to intercept the events related to the <em>managed object</em>, while the second one is used to create new properties and get the events for them as well. Whenever a property is read or written on a <em>DynaObjectProxy</em> instance, the implementation looks for it in the <em>managed object</em> instance through the <em>managedObjProxy</em> and if it&#8217;s not able to find it, then it looks inside the <em>dynamicObjProxy</em>. If the property is still not available, if it has to be read, then a null value is returned, otherwise it is created inside the <em>dynamicObjProxy</em>. The list of all the properties in a <em>DynaObjectProxy</em> instance is the union of both the properties available in the <em>managedObjProxy</em> and the <em>dynamicObjProxy</em>. All the events dispatched by the proxy are in fact dispatched through an internal <em>EventDispatcher</em> instance because we cannot extend that class as we are already extending the <em>Proxy</em> class and ActionScript 3 doesn&#8217;t support multiple inheritance.</p>
<p>So now we can go on with an example application. Let&#8217;s say we want the user to select some fruits that he likes from a list and we want him to be able to specify also their quantity. So a <em>Fruit</em> class could look like this:</p>
<div class="post-source-code">
<pre class="brush: as3;">package com.devahead.model
{
	[Bindable]
	public class Fruit
	{
		public var name: String;
		public var quantity: int;

		public function Fruit(name: String, quantity: int = 0)
		{
			this.name = name;
			this.quantity = quantity;
		}
	}
}</pre>
</div>
<p>What is important, to identify a fruit in our model, are its name and its quantity. But in this way, we don&#8217;t have a property to specify if a fruit is selected or not in a grid, we don&#8217;t want to include it in our model because it&#8217;s only important for user interaction. This is especially true if you think about the <em>Fruit</em> class as a representation of a record in a database on the server side. In a <em>FRUITS</em> table the only things that have a meaning are the name and the quantity. It&#8217;s meaningless to know if a user selected a fruit on the client side interface because we store only the selected fruits in the database.</p>
<p>In the example below, we are able to dynamically add a <em>isFruitSelected</em> property to all the <em>Fruit</em> instances through the <em>DynaObjectProxy</em> while keeping at the same time the original typed instances. This allows us to put all our <em>DynaObjectProxy</em> in the grid&#8217;s <em>dataProvider</em> and the user is able to select the fruits through a checkbox and edit their quantity. When the user is happy with his choices, we are able to get all the selected fruits and we could send them to the sever to store them in a database.</p>
<div class="post-source-code">
<pre class="brush: as3;">&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Dynamic ObjectProxy - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;
	applicationComplete=&quot;{onApplicationComplete(event)}&quot;
	viewSourceURL=&quot;srcview/index.html&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			import com.devahead.utils.DynaObjectProxy;
			import com.devahead.model.Fruit;
			import mx.collections.ArrayCollection;
			import mx.events.FlexEvent;

			[Bindable]
			protected var fruitsList: ArrayCollection = new ArrayCollection();

			protected function onApplicationComplete(event: FlexEvent): void
			{
				// Wrap the Fruit instances in DynaObjectProxy instances
				// so we can add the &quot;isFruitSelected&quot; property dynamically
				// in the grid.
				fruitsList.addItem(new DynaObjectProxy(new Fruit(&quot;Orange&quot;)));
				fruitsList.addItem(new DynaObjectProxy(new Fruit(&quot;Pear&quot;)));
				fruitsList.addItem(new DynaObjectProxy(new Fruit(&quot;Apricot&quot;)));
			}

			protected function getSelectedFruits(): void
			{
				selFruitsArea.text = &quot;SELECTED FRUITS:\n\n&quot;;

				var originalFruitsInstances: ArrayCollection = new ArrayCollection();

				for each (var currFruit: DynaObjectProxy in fruitsList)
				{
					// If the fruit is selected, I add it to the selFruitsArea
					if (currFruit.isFruitSelected)
					{
						selFruitsArea.text += currFruit.name + &quot; (&quot; +
							currFruit.quantity + &quot;)\n&quot;;

						// Get the instance of the Fruit class managed by the
						// DynaObjectProxy.
						originalFruitsInstances.addItem(currFruit.managedObj);
					}
				}

				selFruitsArea.text += &quot;\nORIGINAL INSTANCES OF SELECTED FRUITS:\n\n&quot;;

				for each (var currOriFruit: Fruit in originalFruitsInstances)
				{
					selFruitsArea.text += currOriFruit.name + &quot; (&quot; +
						currOriFruit.quantity + &quot;)\n&quot;;
				}
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:Label text=&quot;Select some fruits, edit their quantity, and press the 'Get selected fruits' button&quot;
		fontWeight=&quot;bold&quot;/&gt;

	&lt;mx:DataGrid width=&quot;300&quot; height=&quot;100&quot; dataProvider=&quot;{fruitsList}&quot;
		editable=&quot;true&quot;&gt;
		&lt;mx:columns&gt;
			&lt;mx:DataGridColumn headerText=&quot;Selected&quot; dataField=&quot;isFruitSelected&quot;
				rendererIsEditor=&quot;true&quot; itemRenderer=&quot;mx.controls.CheckBox&quot;
				editorDataField=&quot;selected&quot; textAlign=&quot;center&quot;/&gt;
			&lt;mx:DataGridColumn headerText=&quot;Name&quot; dataField=&quot;name&quot; editable=&quot;false&quot;/&gt;
			&lt;mx:DataGridColumn headerText=&quot;Quantity&quot; dataField=&quot;quantity&quot;/&gt;
		&lt;/mx:columns&gt;
	&lt;/mx:DataGrid&gt;

	&lt;mx:TextArea id=&quot;selFruitsArea&quot; width=&quot;300&quot; height=&quot;200&quot;/&gt;

	&lt;mx:Button label=&quot;Get selected fruits&quot; click=&quot;{getSelectedFruits()}&quot;/&gt;
&lt;/mx:Application&gt;</pre>
</div>
<p>If you use something like BlazeDS or web services, you know how much is important to keep the server side and the client side model classes synchronized to easily send them back and forth between the client and the server. This is were <em>DynaObjectProxy</em> turns out to be very useful. You can add temporary properties quickly while keeping the original instances intact. I&#8217;ve been using this technique for a very long time and it proved to be useful for me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2009/12/dynamic-objectproxy/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Multiple validators on a single component</title>
		<link>http://www.devahead.com/blog/2009/11/multiple-validators-on-a-single-component/</link>
		<comments>http://www.devahead.com/blog/2009/11/multiple-validators-on-a-single-component/#comments</comments>
		<pubDate>Sun, 29 Nov 2009 17:39:29 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[validators]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=7</guid>
		<description><![CDATA[Sometimes, while using validators in Flex, i needed to have more than one validator connected to a single component, e.g. a TextInput. So, at the beginnig, I tried the naive approach, just create multiple validators and assign to all of them the same source and the same property to validate. After a few tests, I [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/MultipleValidators/MultipleValidators.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/MultipleValidators/srcview/MultipleValidators.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p>Sometimes, while using validators in Flex, i needed to have more than one validator connected to a single component, e.g. a <em>TextInput</em>. So, at the beginnig, I tried the naive approach, just create multiple validators and assign to all of them the same source and the same property to validate. After a few tests, I quickly realized that in Flex, a single component is meant to have <strong>only one validator</strong> associated to it. This is a problem in some situations because I have different validatiors that already do what I need and I just want my component to be considered valid only when <strong>all the validators are valid</strong>. So I investigated more in depth taking a look at the Flex SDK source code and I realized that it&#8217;s by design that I simply cannot do it easily. What usually happens is that <strong>it&#8217;s the last triggered validator that decides if a component is valid or not</strong>. We know that everything is based on events dispatching in Flex and that we cannot know the order in which events reach a particular component, so we also don&#8217;t know what will be the last validator to be triggered for a component. This is especially evident when a form is quite complex and contains a lot of fields that have to be validated.</p>
<p style="padding-bottom:0">What can we do to solve this problem? Here I&#8217;m going to explain what I did about a couple of years ago, when I faced this problem. There are rumors that there should be something available in the next version of the Flex SDK (version 4) that solves the problem, but meanwhile, we can still solve it using the manager class I developed. I&#8217;ve been using it up until now and it always worked as expected without problems. Basically, the class takes care of all the validation events coming from different validators and makes sure that the right validity state is preserved for the component that has been validated. It doesn&#8217;t matter when the events are dispatched, it&#8217;s not important, the final result is:</p>
<ul>
<li>a component is considered <em>VALID</em> if all the validators say that it&#8217;s valid;</li>
<li>a component is considered <em>INVALID</em> if at least one of the validators says that it&#8217;s not valid.</li>
</ul>
<p>Let&#8217;s take a look at the source code now.<span id="more-7"></span> The <em class="highlight">ComponentValidationManager</em> is the class that makes it possible to have multiple validators on a single component. We&#8217;ll call the component that has to be validated as the <em class="highlight">managed component</em> and the validators attached to it the <em class="highlight">managed validators</em>.</p>
<div class="post-source-code">
<pre class="brush: as3;">package com.devahead.utils
{
	import mx.core.UIComponent;
	import mx.validators.Validator;
	import mx.events.ValidationResultEvent;
	import mx.collections.ArrayCollection;
	import mx.events.FlexEvent;

	public class ComponentValidationManager
	{
		protected var _isManagerValid: Boolean = true;
		protected var _managedComponent: UIComponent;
		protected var _managedValidators: Array;
		protected var _isValidationManagementEnabled: Boolean = false;

		// Array of the validators in INVALID state
		protected var _invalidValidators: ArrayCollection = new ArrayCollection();
		protected var _invalidValidationMessages: ArrayCollection = new ArrayCollection();

		/**
		 * Constructor.
		 *
		 * @param managedComponent
		 *   UIComponent managed by the ComponentValidationManager.
		 *   If must not be NULL.
		 * @param managedValidators
		 *   Array of the validators that have to be managed. They must
		 *   all be in VALID state at this time.
		 */
		public function ComponentValidationManager(managedComponent: UIComponent,
			managedValidators: Array)
		{
			// NOTE: I expect that all the managedValidators are VALID at this time

			_managedComponent = managedComponent;
			_managedValidators = managedValidators;

			if (_managedComponent != null &amp;&amp; _managedValidators != null &amp;&amp;
				_managedValidators.length &gt; 0)
			{
				for (var i: int = 0; i &lt; _managedValidators.length; i++)
				{
					if (_managedValidators[i] == null || !(_managedValidators[i] is Validator))
					{
						// NULL values or components that are not subclasses of
						// mx.validators.Validator are not allowed.
						_isManagerValid = false;
						break;
					}
				}

				if (_isManagerValid)
				{
					enableValidationManagement();
				}
			}
		}

		/**
		 * Tells if the ComponentValidationManager is valid.
		 *
		 * @return &quot;True&quot; if the manager is valid (i.e. constructors arguments
		 *         where correct).
		 */
		public function get isManagerValid(): Boolean
		{
			return _isManagerValid;
		}

		/**
		 * Managed component.
		 */
		public function get managedComponent(): UIComponent
		{
			return _managedComponent;
		}

		/**
		 * Managed validators.
		 */
		public function get managedValidators(): Array
		{
			return _managedValidators;
		}

		/**
		 * &quot;True&quot; if the validation management is enabled.
		 */
		public function get isValidationManagementEnabled(): Boolean
		{
			return _isValidationManagementEnabled;
		}

		/**
		 * Enables validation management.
		 */
		public function enableValidationManagement(): void
		{
			if (!_isValidationManagementEnabled)
			{
				// Add the listeners for &quot;VALID&quot; and &quot;INVALID&quot; events generated by
				// the managed validators.
				for each (var v: Validator in _managedValidators)
				{
					v.addEventListener(ValidationResultEvent.VALID, onValidatorValidationEvent);
					v.addEventListener(ValidationResultEvent.INVALID, onValidatorValidationEvent);
				}

				_managedComponent.addEventListener(FlexEvent.VALID, onComponentValidationEvent);
				_managedComponent.addEventListener(FlexEvent.INVALID, onComponentValidationEvent);

				_isValidationManagementEnabled = true;
			}
		}

		/**
		 * Disables validation management.
		 */
		public function disableValidationManagement(): void
		{
			if (_isValidationManagementEnabled)
			{
				_managedComponent.removeEventListener(FlexEvent.INVALID, onComponentValidationEvent);
				_managedComponent.removeEventListener(FlexEvent.VALID, onComponentValidationEvent);

				// Remove the listeners for &quot;VALID&quot; and &quot;INVALID&quot; events generated by
				// the managed validators.
				for each (var v: Validator in _managedValidators)
				{
					v.removeEventListener(ValidationResultEvent.VALID, onValidatorValidationEvent);
					v.removeEventListener(ValidationResultEvent.INVALID, onValidatorValidationEvent);
				}

				_invalidValidators.removeAll();
				_invalidValidationMessages.removeAll();

				_isValidationManagementEnabled = false;
			}
		}

		/**
		 * The managed component has been judged VALID by a validator, so we must
		 * update its state.
		 *
		 * @param validatorInstance
		 *   Validator that judged the managed component as VALID.
		 */
		protected function updateManagedComponentValidState(validatorInstance: Validator): void
		{
			var itemIndex: int = _invalidValidators.getItemIndex(validatorInstance);

			if (itemIndex != -1)
			{
				// Remove the validator from the INVALID list
				_invalidValidators.removeItemAt(itemIndex);

				// Remove also the corresponding validation message
				_invalidValidationMessages.removeItemAt(itemIndex);

				if (_invalidValidators.length == 0)
				{
					// Restore the normal state of the managed component (now it's valid)
					_managedComponent.errorString = null;

					if (_managedComponent.focusManager != null &amp;&amp;
						_managedComponent.focusManager.getFocus() == _managedComponent)
					{
						// The managed component has the focus so we must also
						// draw the border.
						_managedComponent.drawFocus(true);
					}
				}
				else
				{
					// The managed component is still INVALID and due to the fact that
					// the error message previously generated by the validator was
					// removed, we must update the message that should now be displayed
					// for the managed component.
					updateManagedComponentInvalidState();
				}
			}
		}

		/**
		 * The managed component has been judged INVALID by a validator, so we must
		 * update its state.
		 *
		 * @param validatorInstance
		 *   Validator that judged the managed component as INVALID.
		 */
		protected function updateManagedComponentInvalidState(
			validatorInstance: Validator = null, validationMessage: String = &quot;&quot;): void
		{
			var isValidationMessageChanged: Boolean = false;

			if (validatorInstance != null)
			{
				if (!_invalidValidators.contains(validatorInstance))
				{
					// Add the validator the the INVALID list
					_invalidValidators.addItem(validatorInstance);

					// Add the corresponding validation message
					_invalidValidationMessages.addItem(validationMessage);

					isValidationMessageChanged = true;
				}
				else
				{
					// The validation message could have changed, so we update it
					// if necessary.
					var oldValidationMessage: String = String(_invalidValidationMessages.getItemAt(
						_invalidValidators.getItemIndex(validatorInstance)));

					if (oldValidationMessage != validationMessage)
					{
						_invalidValidationMessages.setItemAt(validationMessage,
							_invalidValidators.getItemIndex(validatorInstance));

						isValidationMessageChanged = true;
					}
				}
			}
			else
			{
				if (_invalidValidators.length &gt; 0)
				{
					// We force the update of the INVALID state for the managed component
					isValidationMessageChanged = true;
				}
			}

			if (isValidationMessageChanged)
			{
				// We graphically display the error on the managed component

				// We prepare the error message taking into account all those
				// returned by the managed validators that are in the INVALID state.
				var errorMessage: String = &quot;&quot;;

				for each (var msg: String in _invalidValidationMessages)
				{
					if (errorMessage != &quot;&quot;)
					{
						errorMessage += &quot;\n&quot;;
					}

					errorMessage += msg;
				}

				_managedComponent.errorString = errorMessage;

				if (_managedComponent.focusManager != null &amp;&amp;
					_managedComponent.focusManager.getFocus() == _managedComponent)
				{
					// The managed component has the focus so we must also draw the border
					_managedComponent.drawFocus(true);
				}
			}
		}

		/**
		 * Handler for the validation events coming from the managed component.
		 *
		 * @param event
		 *   Validation event.
		 */
		protected function onComponentValidationEvent(event: FlexEvent): void
		{
			if (event.target == _managedComponent)
			{
				// We check that the INVALID state is kept correctly for the managed
				// component if it is in fact INVALID (this is useful to avoid the
				// interference of the function &quot;validationResultHandler&quot; in
				// mx.core.UIComponent with the management made internally by
				// ComponentValidationManager).
				updateManagedComponentInvalidState();
			}
		}

		/**
		 * Handler for the validation events coming from the managed validators.
		 *
		 * @param event
		 *   Validation event.
		 */
		protected function onValidatorValidationEvent(event: ValidationResultEvent): void
		{
			if (event.type == ValidationResultEvent.VALID)
			{
				updateManagedComponentValidState(Validator(event.target));
			}
			else if (event.type == ValidationResultEvent.INVALID)
			{
				updateManagedComponentInvalidState(Validator(event.target), event.message);
			}
		}
	}
}</pre>
</div>
<p>So, what does this class do? You create an instance of the class specifying which component you want to manage and all the validators that are connected to it, then the class attaches its handlers to catch the validation events and keeps the component updated setting its validation error message accordingly. The validation error message is created as the sequence of all the messages returned by the invalid validators. To better understand how to use <em>ComponentValidationManager</em> we can take a look at the following example.</p>
<div class="post-source-code">
<pre class="brush: as3;">&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Multiple validators on a single component - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;
	applicationComplete=&quot;{onApplicationComplete(event)}&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			import com.devahead.utils.ComponentValidationManager;
			import mx.events.FlexEvent;

			protected const TOO_SHORT_ERROR: String = &quot;String must not be shorter than {0} characters&quot;;
			protected const TOO_LONG_ERROR: String = &quot;String must not be longer than {0} characters&quot;;

			protected var compValManager: ComponentValidationManager;

			protected function onApplicationComplete(event: FlexEvent): void
			{
				compValManager = new ComponentValidationManager(textInput2, [strVal2a, strVal2b]);
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:StringValidator id=&quot;strVal1a&quot; minLength=&quot;1&quot; maxLength=&quot;4&quot;
		source=&quot;{textInput1}&quot; property=&quot;text&quot;
		tooShortError=&quot;{TOO_SHORT_ERROR}&quot; tooLongError=&quot;{TOO_LONG_ERROR}&quot;/&gt;
	&lt;mx:StringValidator id=&quot;strVal1b&quot; minLength=&quot;4&quot; maxLength=&quot;6&quot;
		source=&quot;{textInput1}&quot; property=&quot;text&quot;
		tooShortError=&quot;{TOO_SHORT_ERROR}&quot; tooLongError=&quot;{TOO_LONG_ERROR}&quot;/&gt;

	&lt;mx:StringValidator id=&quot;strVal2a&quot; minLength=&quot;1&quot; maxLength=&quot;4&quot;
		source=&quot;{textInput2}&quot; property=&quot;text&quot;
		tooShortError=&quot;{TOO_SHORT_ERROR}&quot; tooLongError=&quot;{TOO_LONG_ERROR}&quot;/&gt;
	&lt;mx:StringValidator id=&quot;strVal2b&quot; minLength=&quot;4&quot; maxLength=&quot;6&quot;
		source=&quot;{textInput2}&quot; property=&quot;text&quot;
		tooShortError=&quot;{TOO_SHORT_ERROR}&quot; tooLongError=&quot;{TOO_LONG_ERROR}&quot;/&gt;

	&lt;mx:Label text=&quot;Validator A: string length &gt;= 1 and &amp;lt;= 4&quot;/&gt;
	&lt;mx:Label text=&quot;Validator B: string length &gt;= 4 and &amp;lt;= 6&quot;/&gt;
	&lt;mx:Label text=&quot;Only 4 characters strings should be recognized as valid&quot; fontWeight=&quot;bold&quot;/&gt;

	&lt;mx:HBox&gt;
		&lt;mx:Label text=&quot;Write something:&quot;/&gt;
		&lt;mx:TextInput id=&quot;textInput1&quot;/&gt;
		&lt;mx:Button label=&quot;Validate (A -&gt; B)&quot;
			click=&quot;{strVal1a.validate(); strVal1b.validate()}&quot;/&gt;
		&lt;mx:Button label=&quot;Validate (B -&gt; A)&quot;
			click=&quot;{strVal1b.validate(); strVal1a.validate()}&quot;/&gt;
		&lt;mx:Label text=&quot;(without ComponentValidationManager)&quot; fontWeight=&quot;bold&quot;/&gt;
	&lt;/mx:HBox&gt;

	&lt;mx:HBox&gt;
		&lt;mx:Label text=&quot;Write something:&quot;/&gt;
		&lt;mx:TextInput id=&quot;textInput2&quot;/&gt;
		&lt;mx:Button label=&quot;Validate (A -&gt; B)&quot;
			click=&quot;{strVal2a.validate(); strVal2b.validate()}&quot;/&gt;
		&lt;mx:Button label=&quot;Validate (B -&gt; A)&quot;
			click=&quot;{strVal2b.validate(); strVal2a.validate()}&quot;/&gt;
		&lt;mx:Label text=&quot;(with ComponentValidationManager)&quot; fontWeight=&quot;bold&quot;/&gt;
	&lt;/mx:HBox&gt;

&lt;/mx:Application&gt;</pre>
</div>
<p style="padding-bottom:0">In the example, there are a couple of <em>TextInput</em> components and each of them has a couple of validators attached, but only <em>textInpu2</em> is managed by <em>ComponentValidationManager</em>. According to the validators, only strings made by exactly four characters should be considered valid. If you type something in <em>textInput1</em> and you try to click the two buttons next to it, you&#8217;ll see different behaviors:</p>
<ul>
<li>if only <em>Validator A</em> considers the string valid and you click <em>Validate (A -&gt; B)</em>, <em>textInput1</em> will be displayed as <em>INVALID</em> because the last validation has been executed by <em>Validator B</em>, while if you click <em>Validate (B -&gt; A)</em> the text field will be considered valid because the last validation has been executed by <em>Validator A</em>;</li>
<li>if only <em>Validator B</em> considers the string valid and you click <em>Validate (B -&gt; A)</em>, <em>textInput1</em> will be displayed as <em>INVALID</em> because the last validation has been executed by <em>Validator A</em>, while if you click <em>Validate (A -&gt; B)</em> the text field will be considered valid because the last validation has been executed by <em>Validator B</em>;</li>
<li>if both the validators consider the string valid, then there are no problems and <em>textInput1</em> is displayed as <em>VALID</em>;</li>
<li>if both the validators consider the string invalid, then the validation error message displayed as a hint while moving over the text field with the mouse pointer will be the message returned by the last validator that executed the validation.</li>
</ul>
<p>If you try to repeat the same tests with <em>textInput2</em>, you&#8217;ll see that the validity of the component is always kept in the correct state and also the validation error hint reflects the real state of the field. This happens thanks to <em>ComponentValidationManager</em>, so you don&#8217;t care when the validation occurs in different validators, you just connect them to your text field and everything is fine.</p>
<p>What we saw can be applied to every kind of <em>UIComponent</em> and every kind of validators. I hope this will be useful to somebody, for me it was. If you develop your own procedure to automatically create <em>ComponentValidationManager</em> instances for all the validators in a form, everything could become transparent to the developer. We&#8217;ll see in other posts something that can be useful to execute such a task.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2009/11/multiple-validators-on-a-single-component/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
